Why doesn’t `std::initializer_list` provide a subscript operator?

According to Bjarne Stroustrup in Section 17.3.4.2 (p. 497) of The C++ Programming Language, 4th Edition: Unfortunately, initializer_list doesn’t provide subscripting. No further reason is given. My guess is that it’s one of these reasons: it’s an omission, or because the initializer_list class is implemented with an array and you’d have to do bounds checking … Read more

Initialize multiple constant class members using one function call C++

In general, is there a way to do this without wasted function calls or memory? Yes. This can be done with a delegating constructor, introduced in C++11. A delegating constructor is a very efficient way to acquire temporary values needed for construction before any member variables are initialized. int gcd(int a, int b); // Greatest … Read more

Brace-enclosed initializer list constructor

It can only be done for aggregates (arrays and certain classes. Contrary to popular belief, this works for many nonpods too). Writing a constructor that takes them is not possible. Since you tagged it as “C++0x”, then this is possible though. The magic words is “initializer-list constructor”. This goes like Phenotype(std::initializer_list<uint8> c) { assert(c.size() <= … Read more

Why does the number of elements in a initializer list cause an ambiguous call error?

What is happening here is that in the two element initializer list both of the string literals can be implicitly converted to const char* since their type is const char[N]. Now std::vector has a constructor that takes two iterators which the pointers qualify for. Because of that the initializer_list constructor of the std::vector<std::string> is conflicting … Read more

Why isn’t `std::initializer_list` defined as a literal type?

The standard committee seems to intend on initializer_list being a literal type. However, it doesn’t look like it’s an explicit requirement, and seems to be a bug in the standard. From ยง 3.9.10.5: A type is a literal type if it is: – a class type (Clause 9) that has all of the following properties: … Read more

Convert a vector to initializer_list

The answer is NO, you cannot do that. An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type T. A std::initializer_list object is automatically constructed when: a braced-init-list is used in list-initialization, including function-call list initialization and assignment expressions (not to be confused with constructor … Read more