C ++ 0x nested initializer lists

I would like to use the C ++ 0x initializer list function to initialize std :: vector with a given time of the number of elements for the new API I'm working on. Something like that:

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 you have any idea how to do this? Is it possible? I know that I will need to use TMP and recursion to create a list of duplicate strings and finally access it through a constant (e.g. enumeration). But it seems like I can't even put in a list of initializers like this.

+6
source share
1 answer

You cannot insert initializer lists to expand them, and you cannot add / merge them. To access an array of compile-time size, this is just some syntactic sugar. Even copying initializer_lists does not copy their elements. Most importantly, this means that you cannot use the return value of the duplicate! The referenced array is destroyed when the function returns, for 8.5.4p6 in N3290:

The array lifetime is the same as the initializer_list object.

(Temporarily created in the return statement, and then returned with a value. Even if copying occurs, all other copy semantics are not changed.)

Compare, for example, with the temporary initializer_list created here, which is then passed to ctor and destroyed after the object is initialized, at the same time, all other temporary objects in the same full expression (if any) should be destroyed:

 vector<string> v {"foo"}; 

Instead of manipulating the initializer lists, use the vector method to insert N copies:

 v.insert(v.end(), 3, "bar"); 
+8
source

Source: https://habr.com/ru/post/887004/


All Articles