我正在尝试使用 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
会包含狗和猫通用的构造函数和运算符。一种倒置多态,其中基类具有专业化。这样做的原因是构造函数和运算符不必为每个特化重写或转发。