c++ covariant constructions with respect to template parameters

Viewed 80

I have a base class and its derived class with pointers to forward declared classes:

class BaseParam;

template <class S = BaseParam> class Base;

class BaseParam {
private:
    std::unique_ptr<Base<>> ptr;
public:
    virtual const Base<>& get_ptr() const {return *ptr;}
};

And similarly for its derived class

class DerivedParam;

template <class S = DerivedParam> class Derived;

class DerivedParam : public BaseParam {
private:
    std::unique_ptr<Derived<>> ptr;
public:
     const Derived<>& get_ptr() const override {return *ptr;}  // <---- Here we'll have trouble
};

The above mentioned class templates are also intertwined with the Param versions, here's the prototype:

template <class S>
class Base {
private:
    std::unique_ptr<S> ptr;
    // ...
public:
    // ...
    const S& get_ptr() const { return *ptr; }
};

template <class S>
class Derived : public Base<S> {
};

So that Derived = Derived<DerivedParam> inherits from Base<DerivedParam> But in order to make the return marked with <-- above covariant, we would need Derived to inherit from Base = Base<BaseParam>. How does one do this in a clean fashion? I cannot add an extra inheritance say like

template <class S>
class Derived: public Base<S>, public virtual Base<>

Cause Base and Base<DerivedParam> will hold two different pointers to BaseParam and to DerivedParam. Since a pointer to DerivedParam decays to one to BaseParam there should be a solution where the base class holds only one pointer.

So what I am asking is if there is some functorial way of defining class inheritance for class templates.

0 Answers
Related