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;
}
?