C ++ 11 initializer_list constructor marked as "explicit"

Is it possible to use explicit with init-list ctor to make sure that an expression like {a} does not lead to an unexpected implicit conversion? And one more thought: should I worry about this? Writing {a} less likely to be a mistake than just a , but, on the other hand, it may still be unclear from the code that we create the object through implicit conversion.

 class Foo { explicit Foo (std::initializer_list<Bar> ilist) { /*...*/} }; 
+4
source share
2 answers

You can not. This leads to an unexpected implicit conversion.

However, unexpected implicit conversion is not allowed, and the compiler will reject your program. This, however, does not prevent the compiler from choosing or considering it. Example

  void f(Foo); void f(std::vector<Bar>); int main() { // ambiguous f({bar1, bar2, bar3}); } 
+1
source

Of course you can. It doesn't matter if you really have to be dependent on the situation, although I think that would be rare in general.

0
source

All Articles