Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 奇怪的重复模板变化_C++_Templates_Crtp - Fatal编程技术网

C++ 奇怪的重复模板变化

C++ 奇怪的重复模板变化,c++,templates,crtp,C++,Templates,Crtp,关于我是否要实现它的一个微小变化(使用模板参数),我得到一个编译错误: template <template <typename T> class Derived> class Base { public: void CallDerived() { Derived* pT = static_cast<Derived*> (this); pT->Action(); // instantiation invoc

关于我是否要实现它的一个微小变化(使用模板参数),我得到一个编译错误:

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()
    {
    }
};
模板
阶级基础
{
公众:
void CallDerived()
{
导出*pT=静态_转换(本);
pT->Action();//此处实例化调用错误
}
};
模板
派生类:公共基
{
公众:
无效行动()
{
}
};
我不确定人们会选择这个表单(它不是为我编译的)而不是使用这个表单(这个很有效)

模板
阶级基础
{
公众:
void CallDerived()
{
导出*pT=静态_转换(本);
pT->Action();
}
};
模板
派生类:公共基
{
公众:
无效行动()
{
}
};

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

template <template <typename T> class Derived>
class Base
{
     //..
};
模板
阶级基础
{
//..
};
所以这段代码没有意义:

Derived* pT = static_cast<Derived*> (this);
pT->Action(); // instantiation invocation error here
Derived*pT=static\u cast(此);
pT->Action();//此处的实例化调用错误
这里的
Derived
是一个模板参数,它需要您没有提供给它的模板参数。事实上,在
CallDerived()
函数中,您无法知道需要为其提供的类型,以便执行您想要执行的操作


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

这也应该可以编译。我们只需要显式地指定另一个模板参数

 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()
    {
    }
};
模板
阶级基础
{
公众:
void CallDerived()
{
导出*pT=静态_转换(本);
pT->Action();//此处实例化调用错误
}
};
模板
派生类:公共基
{
公众:
无效行动()
{
}
};

但如何在第一种情况下提供模板参数。。使用派生*pt不起作用either@Ghita:
T
在基类中是未知的。另一种解决方案解释了如何将
T
传递到基。但这不是必需的,因为您应该使用第二种解决方案。有时基类中需要T。例如,当有一个成员
T 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()
    {
    }
};