C++ CRTP中的模板化派生类(奇怪的重复模板模式)
我使用了不使用g++4.2.1编译的CRTP,可能是因为派生类本身就是一个模板?有人知道为什么这不起作用,或者更好的是,知道如何让它起作用吗?下面是示例代码和编译器错误 资料来源:foo.CC++ CRTP中的模板化派生类(奇怪的重复模板模式),c++,templates,crtp,C++,Templates,Crtp,我使用了不使用g++4.2.1编译的CRTP,可能是因为派生类本身就是一个模板?有人知道为什么这不起作用,或者更好的是,知道如何让它起作用吗?下面是示例代码和编译器错误 资料来源:foo.C #包括 使用名称空间std; 模板结构foo; 模板结构栏:foo { X evaluate(){return static_cast(5.3);} }; 模板结构baz:foo { X evaluate(){return static_cast(“elk”);} }; 模板结构foo:D { X运算符()
#包括
使用名称空间std;
模板结构foo;
模板结构栏:foo
{
X evaluate(){return static_cast(5.3);}
};
模板结构baz:foo
{
X evaluate(){return static_cast(“elk”);}
};
模板结构foo:D
{
X运算符(){return static_cast(this)->evaluate();}
};
模板
无效打印_foo(foo xyzx)
{
coutCRTP的思想是让基类知道其导数的类型,而不是让基类从其导数派生。
否则会出现以下情况:
派生的
派生自基
,它
- 派生自
派生的
,其中
- 派生自
Base
,其中
请改用以下方法:
template<typename X, typename D> struct foo // : D
// ... ^ remove that
模板结构foo/:D
//…^
有一种方法可以使CRTP适用于模板派生类,但需要注意的是,它应该始终是模板
#include <iostream>
#include <typeinfo>
template<template <class> class Derived, class T>
struct A{
void interface(){
static_cast<Derived<T>*>(this)->impl();
}
};
template<class T>
struct B: public A<B, T>
{
void impl(){
std::cout << "CRTP with derived templates are real\n";
std::cout << "Tempate argument is " << typeid(T).name() << "\n";
}
};
int main(void)
{
B<char>().interface();
B<double>().interface();
B<void>().interface();
return 0;
}
#包括
#包括
模板
结构A{
void接口(){
静态_cast(this)->impl();
}
};
模板
结构B:公共A
{
void impl(){
std::谢谢,我不知道为什么我没早点听清楚。@Butterwaffle,那是因为:D-是非常有趣的微笑,你不想删除它:D
template<typename X, typename D> struct foo // : D
// ... ^ remove that
#include <iostream>
#include <typeinfo>
template<template <class> class Derived, class T>
struct A{
void interface(){
static_cast<Derived<T>*>(this)->impl();
}
};
template<class T>
struct B: public A<B, T>
{
void impl(){
std::cout << "CRTP with derived templates are real\n";
std::cout << "Tempate argument is " << typeid(T).name() << "\n";
}
};
int main(void)
{
B<char>().interface();
B<double>().interface();
B<void>().interface();
return 0;
}