如何结束模板图层

how to end-up template layers?

本文关键字:图层 结束 何结束      更新时间:2023-10-16

template <typename Super>
class Whatever : public Super
{
    ...
};

是可能的,创建Whatever类没有派生的东西?

这是较轻的版本吗?

struct BlankType{};
Whatever<BlankType> w;

////////////////////////////////////////

一些背景:

我有我的代码组成的模板层像上面的Whatever。所以我可以输入:

typedef Whatever<Whenever<Wherever<>>>> MyCombinedType

实际上我不能。我必须做

typedef Whatever<Whenever<Wherever<BlankType>>>> MyCombinedType

,类型也变为BlankType。我不能让Wherever"不可分层",因为当我做的只是

typedef Whatever<Whenever<>>> MyCombinedType

如果您想创建Whatever类,而不是从派生的东西,您可以简单地定义其规范如下:

class BlankType {};
template<typename T = BlankType> class Whatever : public T {};
template<> class Whatever<BlankType> {};

有点跑题了,在使用可变模板的c++中,由于递归定义,您可以避免递归实例化:

template <class ...Bases> class Whatever;
template <class B, class ...Bases>
class Whatever<B, Bases...> : public B, public Whatever<Bases...> { /* ... */ };
template <class B>
class Whatever<B> : public B { /*... */ };
template <> class Whatever<> { /* ... */ };

现在你可以输入Whatever<Foo, Bar, Baz>并从所有这些继承。如果您还想从多个嵌套的Whatever的其他实例继承,您应该使所有的继承都是虚拟的。

我的示例中的最后一个专门化还展示了如何专门化Whatever,使其不从任何东西派生。如果你写Whatever<> x;,你有一个类的对象,它不从任何东西派生。