Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ CRTP with parametized base class?

I am trying to use CRTP with a small variation. I have one derived class template and wish to apply this to multiple base classes. But this is either impossible or I just can't get the syntax right. The following code does not compile but hopefully illustrates what I want to achieve:

template <class Derived> struct BaseCats { /* ... */ };
template <class Derived> struct BaseDogs { /* ... */ };
// ....
template <class Derived> struct BaseN { /* ... */ };

template <template <class> class Base>
struct Wrapper 
    : 
    Base<Wrapper> // compile error - Wrapper is not a complete type
{
    Wrapper(int n) 
    { 
       // I do not want to rewrite or forward this 
       // constructor or Wrapper's operators
    }
};

typedef Wrapper<BaseCats> Cats;
typedef Wrapper<BaseDogs> Dogs;
// ...
typedef Wrapper<BaseN> MyTypeN;

Can this be done?

Edit:

What am I trying to achieve here?

I renamed some of the code above to use a "dogs and cats" metaphor. There might exists functions such as:

void BaseCats<Derived>::print() const 
{ 
    std::cout << (static_cast<const Derived *>this)->n << " cats\n"; 
}

But Wrapper would contain constructors and operators that are common to both dogs and cats. Kind of inverted polymorphism where the base class has the specializations. The reason for doing things this way around is so that constructors and operators do not have to be rewritten or forwarded for each specialization.

like image 712
paperjam Avatar asked Feb 17 '26 13:02

paperjam


1 Answers

Your compile error can be solved by this:

Base<Wrapper<Base> >

You forgot the template arguments.

like image 89
Pubby Avatar answered Feb 19 '26 03:02

Pubby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!