I have a class with two constructors:
myclass(std::initializer_list<int>);
myclass(std::initializer_list<std::initializer_list<int>);
The following declarations work
myclass obj1 = {{1,2},{3,4},{5,6}}; //a 3x2 matrix
myclass obj2 = {{1,2,3}}; // a 1x3 matrix
But the following declaration does not work, when I try to compile, it says that it is ambiguous
myclass obj3 = {{1},{2},{3}}; //a 3x1 matrix
The following solves the problem:
myclass obj3 = {std::initializer_list<int>({1}),
std::initializer_list<int>({2}),
std::initializer_list<int>({3})};
but I find this solution unconfortable and ugly. Is it possible to do something better?
The reason the compiler says {{1},{2},{3}}
is ambiguous is that {1}
can both be an int
or an std::initializer_list<int>
. So you either have a list of int
s or a list of a list of int
s and the compiler cannot decide what you actually want
When you do {{{1},{2},{3}}}
or {{{1}},{{2}},{{3}}}
the innermost braces represents an int
, the next innermost represents a list of those int
s and then the outermost braces represents a list of that list. You needs these extra braces to remove the ambiguity for the compiler.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.