简体   繁体   中英

C++11 initializer_list constructor marked “explicit”

Can I use explicit with an init-list ctor to make sure an expression like {a} doesn't result in unexpected implicit conversion? And another thought: should I be worried about it? Writing {a} is less likely to be a mistake than simply a , but on the other hand, it still may not be clear from the code that we're constructing an object through implicit conversion.

class Foo
{
    explicit Foo (std::initializer_list<Bar> ilist) { /*...*/}
};

You cannot. It does result in the unexpected implicit conversion.

However, the unexpected implicit conversion is disallowed and the compiler will reject your program. That however doesn't stop the compiler to select or consider it. Example

 void f(Foo);
 void f(std::vector<Bar>);

 int main() {
   // ambiguous
   f({bar1, bar2, bar3});
 }

You certainly can. Whether you should really depends on the situation, although I think it would be rare in general.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM