带有参数化基类的c++ CRTP

C++ CRTP with parametized base class?

本文关键字:c++ CRTP 基类 参数      更新时间:2023-10-16

我正在尝试使用CRTP与一个小的变化。我有一个派生类模板,并希望将其应用于多个基类。但这要么是不可能的,要么就是我的语法不对。下面的代码无法编译,但希望能说明我想要实现的目标:

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;

这能做到吗?

编辑:

我想达到什么目的?

我重命名了上面的一些代码,以使用"狗和猫"的比喻。可能存在如下函数:

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

但是Wrapper将包含狗和猫共同的构造函数和操作符。一种反向多态性,基类具有专门化。这样做的原因是不必为每个特化重写或转发构造函数和操作符。

你的编译错误可以这样解决:

Base<Wrapper<Base> >

你忘记了模板参数