0

Some cpp class accept initializer_list as input, for example:

std::map<std::string, int> m{{"CPU", 10}, {"GPU", 15}, {"RAM", 20}}; 

or

std::map<std::string, int> m={{"CPU", 10}, {"GPU", 15}, {"RAM", 20}}; 

Is it possible, to define an initializer_list variable, then use it to call the constructor? i.e. something like:

auto il = {{"CPU", 10}, {"GPU", 15}, {"RAM", 20}}; std::map<std::string, int> m = il; 
3
  • 3
    Note that initializer_list is a proxy object, it does not actually hold values. So using it as a universal storage to pass stuff around is not a good idea. Commented May 4, 2024 at 19:48
  • @user7860670 could you elaborate a bit more on why? Commented May 4, 2024 at 20:58
  • 1
    see stackoverflow.com/questions/15286450 Commented May 5, 2024 at 7:14

2 Answers 2

3

Yes. Example:

#include <initializer_list> #include <map> #include <string> int main() { std::initializer_list<std::pair<const std::string, int>> il = { {"CPU", 10}, {"GPU", 15}, {"RAM", 20}}; std::map<std::string, int> m = il; } 
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it's possible. You only need to specify the value type of the initializer list explicitly.

#include <map> #include <string> int main() { using map = std::map<std::string, int>; auto il = {map::value_type{"CPU", 10}, {"GPU", 15}, {"RAM", 20}}; std::map<std::string, int> m = il; } 

or

#include <map> #include <string> #include <utility> int main() { auto il = { std::pair<const std::string, int>{"CPU", 10}, {"GPU", 15}, {"RAM", 20}}; std::map<std::string, int> m = il; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.