struct Foo
{
    explicit Foo(int a):m(a){}
    int padd1, m, padd2;
};
void Bar(Foo){}
int main()
{
    Bar(11); // OK, gives error
    auto x = static_cast<Foo>(37);
    x.m;
}
Is it ok, that static_cast construct Foo object even though its constructor is marked explicit?
It works in MSVC2013 and GCC http://ideone.com/dMS5kB
Yes, static_cast will use the explicit constructor.
5.2.9 Static cast [expr.static.cast]
4 An expression e can be explicitly converted to a type T using a static_cast of the form
static_cast<T>(e)if the declarationT t(e);is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With