The constructor is always used instead of the explicit conversion operator.

I have the following class:

template <typename T1>
class Foo {
public:
    Foo(T1* obj) : obj(obj) {}

    template <typename T2>
    Foo(const Foo<T2>& other) : obj(other.obj) {}

    template <typename T2>
    explicit operator Foo<T2>() {
        return Foo<T2>(static_cast<T2*>(obj));
    }
    T1* obj;
};

The purpose of the second constructor is that an implicit conversion from Foo<X>to is Foo<Y>allowed if an implicit conversion from X*to is allowed Y*.

Here we use the conversion operator, which allows an explicit conversion from Foo<X>to Foo<Y>with an explicit conversion from X*to Y*.

But I noticed that the conversion operator is never used. The compiler always uses the second constructor, even if I am doing an explicit cast. This causes an error if implicit conversion of base types is not possible.

The following code can be used to test the class above.

class X {};
class Y : public X {};

int main() {
    Y obj;
    Foo<Y> y(&obj);
    Foo<X> x = y; // implicit cast works as expected.
    // y = x; // implicit conversion fails (as expected).
    // y = static_cast<Foo<Y>>(x); // conversion fails because constructor is
                                   // called instead of conversion operator.
}

?

+4
2

static_cast<Foo<Y>>(x); Foo<Y> x ( Foo<X>) , .

( )

, , , .

struct To {
    To() = default;
    To(const struct From&) {} // converting constructor
};

struct From {
    operator To() const {return To();} // conversion function
};

int main()
{
    From f;
    To t1(f); // direct-initialization: calls the constructor
// (note, if converting constructor is not available, implicit copy constructor
//  will be selected, and conversion function will be called to prepare its argument)
    To t2 = f; // copy-initialization: ambiguous
// (note, if conversion function is from a non-const type, e.g.
//  From::operator To();, it will be selected instead of the ctor in this case)
    To t3 = static_cast<To>(f); // direct-initialization: calls the constructor
    const To& r = f; // reference-initialization: ambiguous
}

SFINAE; .. , .

template <typename T2, typename = std::enable_if_t<std::is_convertible<T2*, T1*>::value>>
Foo(const Foo<T2>& other) : obj(other.obj) {}

LIVE

+4

[expr.static.cast/4]

e T static_cast static_cast<T>(e), T t(e); , T (8.5). , , . e glvalue , lvalue.

, , , .

+2

Source: https://habr.com/ru/post/1681556/


All Articles