c++ - C++0x nested initializer lists -


i use c++0x new initializer list feature initialize std::vector compile time defined number of items new api i'm working on. this:

template<int n> std::initializer_list<std::string> duplicate(std::string s) {   // return s duplicated n times   return { s, s, s }; }  std::vector<std::string> v = { "foo",  duplicate<3>("bar") }; 

do have idea how accomplish this? possible? i'm aware of need use tmp , recursion build list of duplicated strings , access somehow through constant (e.g., enum). seems cannot nest initializer list this.

you cannot nest initializer lists in order extend them, nor can add/concatenate them. bit of syntactic sugar access compile-time-sized array. copying initializer_lists doesn't copy items. importantly, means cannot use return value of duplicate! referenced array destroyed when function returns, per 8.5.4p6 in n3290:

the lifetime of array same of initializer_list object.

(a temporary created in return statement , returned value. if copy elision happens, other semantics of copying unchanged.)

compare to, example, temporary initializer_list created here, passed ctor , destroyed after object initialized, @ same point other temporary objects in same full expression (if there any) destroyed:

vector<string> v {"foo"}; 

instead of manipulating initializer lists, use vector's method insert n copies:

v.insert(v.end(), 3, "bar"); 

Comments