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()时当然,您可以使用一个traits类,为每个派生类提供一个T,但有时您希望T和派生类独立变化。在这种情况下,您需要使用带有模板+模板参数的[first]方法。。。我真的不明白为什么我刚刚意识到,派生函数也必须传输它的t参数。
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()
{
}
};