Is it possible to make the following work? Basically I want Ptr<B> to be an acceptable return type replacement for Ptr<A>.
template<typename T>
class Ptr {
public:
explicit Ptr (T * ptr) : ptr(ptr) {}
T * ptr;
};
class A {
virtual Ptr<A> foo () {
return Ptr<A>(NULL);
}
};
class B : public A {
virtual Ptr<B> foo () { // BAD! Ptr<B> is not compatable
return Ptr<B>(NULL);
}
};
Your can use curiously recurring templates to replace virtual function overloads with template function returns. The following article might help:
http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
Also check the following code:
template <class C_>
class A_Base {
Ptr<C_> foo() {
return static_cast<C_*>(this)->foo_impl();
}
}
class A : public A_Base<A> {
Ptr<A> foo_impl() { return Ptr<A>(NULL); }
}
class B : public A_Base<B> {
Ptr<B> foo_impl() { return Ptr<B>(NULL); }
}
According to the standard:
The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteria:
So in your example the return types are not really covariant (they are not pointers nor references) and moreover Ptr<B> and Ptr<A> are unrelated types.
So keeping foo virtual and returning Ptr<A> in A and Ptr<B> in B is not possible. If you can/are willing to drop virtual than you can use something in the lines of Cem Kalyoncu's proposal or a variation of it.
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