奇怪的重复模板 - 变体

Curiously recurring template - variation

本文关键字:变体      更新时间:2023-10-16

关于CRP,如果我想实现它的轻微变化(使用模板模板参数(,我会收到编译错误:

template <template <typename T> class Derived>
class Base
{
public:
    void CallDerived()
    {
        Derived* pT = static_cast<Derived*> (this);
        pT->Action(); // instantiation invocation error here
    }
};
template<typename T>
class Derived: public Base<Derived>
{
public:
    void Action()
    {
    }
};

我不完全确定人们会选择这种形式(它不能为我编译(而不是使用它(这有效(

template <typename Derived>
class Base
{
public:
    void CallDerived()
    {
        Derived* pT = static_cast<Derived*> (this);
        pT->Action();
    }
};
template<typename T>
class Derived: public Base<Derived<T>>
{
public:
    void Action()
    {
    }
};

这也应该编译。我们只需要显式指定其他模板参数

 template <typename T, template <typename T> class Derived>
 class Base
 {
 public:
     void CallDerived()
     {
        Derived<T>* pT = static_cast<Derived<T>*> (this);
        pT->Action(); // instantiation invocation error here
     }
 };
template<typename T>
class Derived: public Base<T,Derived>
{
public:
    void Action()
    {
    }
};

在第一个示例中,类模板实际上采用模板模板参数,而不仅仅是模板参数,正如您所写的那样:

template <template <typename T> class Derived>
class Base
{
     //..
};

所以这段代码没有意义:

Derived* pT = static_cast<Derived*> (this);
pT->Action(); // instantiation invocation error here

这里Derived是一个模板模板参数,它需要您没有提供给它的模板参数。实际上,在CallDerived()函数中,您无法知道需要向其提供哪种类型才能执行打算执行的操作。

第二种方法是正确的解决方案。使用它。