Home > Software design >  How to solve the problem that the subclass inherits the base class and meanwhile the base class is a
How to solve the problem that the subclass inherits the base class and meanwhile the base class is a

Time:06-20

#include <iostream>
 using namespace std;
 
 template <typename Child>
 struct Base
 {
     void interface()
     {
         static_cast<Child*>(this)->implementation();
     }
 };
 
 template<typename T,
     template<class T> class Base
 >
 struct Derived : Base<Derived >
 {
     void implementation(T t=0)
     {
          t = 0;
         cerr << "Derived implementation----" << t;
     }
 };



 int main()
 {
     Derived<int,Base<Derived>> d; //Base class as a template parameter is must  
     d.interface();  // Prints "Derived implementation"
 
     return 0;
 }

I hope Derived class inherits from a template parameter Base class,meanwhile hope the instance of Base class depend on Derived class, the Derived class have another template parameter T,I have tried many ways but can't solve it .

Base class as a template parameter is must

I have simplified the source code, but these conditions I describe are necessary.

Now I hope that under these conditions I describe, I can call the interface() sucessfully

Does anyone know where the problem is and how to fix it?

CodePudding user response:

You need to pass a T to Derived<T>::implementation, so Base::interface must have one. The easiest way to do that is make Base::interface a template.

#include <iostream>

template <typename Child>
struct Base
{
    template <typename U>
    void interface(U u)
    {
        static_cast<Child*>(this)->implementation(u);
    }
};

template<typename T>
struct Derived : Base<Derived<T>>
{
    void implementation(T t)
    {
        std::cerr << "Derived implementation----" << t;
    }
};

int main()
{
    Derived<int> d;
    d.interface(1);
}

See it on coliru

CodePudding user response:

template<typename T, 
        template <typename> typename Base>
struct Derived : Base<Derived<T, Base>>
{
    void implementation(T t=0)
    {
        t = 0;
        cerr << "Derived implementation----" << t;
    }
};

Derived<int, Base> d;
d.interface();  // Prints "Derived implementation"

Online Demo

  • Related