Covariant return type with template container

Can the following work be done? 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);
    }
};
+3
source share
3 answers

In accordance with the standard:

The return type of an overriding function must either be identical to the return type of an overridden function, or covariant with function classes. If the function D :: f overrides the function B :: f, the returned function types are covariant if they satisfy the following criteria:

  • both are class pointers or class references
  • B:: f , D:: f , D:: f D
  • cv-, D:: f cv-, cv-qualification, B:: .

, ( ), Ptr<B> Ptr<A> .

, foo virtual Ptr<A> Ptr<B> B . / , - Cem Kalyoncu .

+1

. :

http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

:

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); }
}
+2

You can try something like this:

template<class T> class Ptr
{
...
};

template<class T> class A
{
    virtual Ptr<T> foo();
};

class B : public A<B>
{
    virtual Ptr<B> foo();
};
0
source

All Articles