繁体   English   中英

具有参数化基类的C ++ CRTP?

[英]C++ CRTP with parametized base class?

我正在尝试使用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 << " cats\n"; 
}

但是Wrapper将包含猫和狗通用的构造函数和运算符。 基类具有专门性的一种倒态多态性。 之所以这样做,是因为不必为每个专业化都重写或转发构造函数和运算符。

您的编译错误可以通过以下方法解决:

Base<Wrapper<Base> >

您忘记了模板参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM