简体   繁体   中英

Passing an initializer list to a vector based constructor

I currently have the following code

class test
{
   public:
   test(std::vector<std::string> str)
   {
   }
   test()
   {
   }
    const std::multimap<int,  std::multimap<int, test>> _var= {
                 {0x01,  {
                            {
                                0x0f, {"A", "B", "C", "D"}
                            }
                         }
                 }
        };   
};

int main()
{  
  test t;
}

Error:

main.cpp:29:9: error: could not convert '{{1, {{15, {"A", "B", "C", "D"}}}}}' from '<brace-enclosed initializer list>' to 'const std::multimap<int, std::multimap<int, test> >'
         };
         ^

I wanted to know why passing {"A", "B", "C", "D"} to std::vector<std::string> str) is failing ? Any suggestions on how I can resolve this issue ?

You need another pair of braces. Use:

0x0f, {{"A", "B", "C", "D"}}

Without that, the compiler tries to construct a test using the arguments "A", "B", "C", "D" , as if test{"A", "B", "C", "D"} , which does not work.

This will work:

class test
{
   public:
   test(std::vector<std::string> str)
   {
   }
   test()
   {
   }
    const std::multimap<int,  std::multimap<int, test>> _var= {
                 {0x01,  {
                            {
                                0x0f, std::vector<std::string>{"A", "B", "C", "D"}
                            }
                         }
                 }
        };   
};

Nevertheless, you should never pass containers by value.

An alternative approach is to use an std::initializer_list in your ctor, then your code can be written as:

class test
{
   public:
   test(std::initializer_list<std::string> str)
   {
   }
   test()
   {
   }
    const std::multimap<int,  std::multimap<int, test>> _var= {
                 {0x01,  {
                            {
                                0x0f, {"A", "B", "C", "D"}
                            }
                         }
                 }
        };   
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM