2011-06-27 CPlusPlus0X

Initializer lists

How many times have you not wanted to easily initialize a container with a list of values. Instead you would have to solve that with repeated push_backs either inline or in a loop over a good old C array that could be initialized with the brace notation. C++2011 now fixes this by introducing the initializer_list-template.

It works like this. Constructors and a other functions can take a parameter of type std::intitializer_list:

void function(initializer_list<string> list) 
{ 
   cout << "Number of args are " << list.size() << endl; 
   for (auto it = list.begin(); it != list.end(); ++it) 
   { 
      cout << "List contains: " << (*it) << endl; 
   } 
} 

You can call function like this:

   function({"hi", "ho", "foo", "bar"});

The standard library classes implements this so we can now initialize a vector of strings with either of these ways:

   vector<string> v1 = {"hi", "ho", "foo", "bar"}; 
   vector<string> v2 {"hi", "ho", "foo", "bar"}; 

So this adds yet another feature that makes C++ just a little more convenient to use, easier on the typing and makes the code cleaner and easier to understand.