It seems empirically that C++ always prefers a list initializer over a value initializer. My question is thus how can I force value initialization of a type that also supports a direct list initialization. Here is a minimal non-working example:
#include <initializer_list>
using namespace std;
struct foo {
foo(int) {}
foo(initializer_list<char>) {}
};
struct bar {
foo f{256};
};
In this example, I would like f to be initialized using the constructor foo(int) rather than the foo(initializer_list<char>). However, both GCC and Clang reject the code because 256 is too big for a char, which means the C++ spec requires choosing the list initializer. Obviously commenting out the second constructor of foo fixes the problem. What's the easiest way to define bar so as to use value initialization on field f? Ideally I could avoid copy initializing f, because in my real example there is no copy constructor.
update
To clarify: of course it's possible to initialize f explicitly in every single constructor of bar. But my question is specifically about the member initialization syntax because in situations with huge numbers of constructors it is preferable just to initialize certain fields in one place rather than to copy the code all over.
foo f(256);.initializer_list<char>is a viable constructor for{256}. Also it is not safe to infer things about the spec based on compiler behaviour. Sometimes multiple compilers get the same thing wrong.initializer_list<char>is a viable constructor for{256}" Because the standard always prefersinitializer_listconstructors where possible, and 256 is implicitly convertible to achar. Therefore it is possible. However, it is illegal since the conversion of 256 to acharis a narrowing conversion, which is not allowed in a braced-init-list.foo f(256)does not work, because that is illegal member declaration syntax. E.g., g++ says, "error: expected identifier before numeric constant".