What could go wrong if copy-list-initialization allowed explicit constructors?

Conceptually copy-list-initialization is the conversion of a compound value to a destination type. The paper that proposed wording and explained rationale already considered the term “copy” in “copy list initialization” unfortunate, since it doesn’t really convey the actual rationale behind it. But it is kept for compatibility with existing wording. A {10, 20} pair/tuple value … Read more

initializer_list and template type deduction

Your first line printme({‘a’, ‘b’, ‘c’}) is illegal because the template argument T could not be inferred. If you explicitly specify the template argument it will work, e.g. printme<vector<char>>({‘a’, ‘b’, ‘c’}) or printme<initializer_list<char>>({‘a’, ‘b’, ‘c’}). The other ones you listed are legal because the argument has a well-defined type, so the template argument T can … Read more

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