Templated derived class in CRTP (Curiously Recurring Template Pattern)
我使用了不使用g++4.2.1编译的crtp,也许是因为派生类本身就是一个模板?有人知道为什么这不起作用,或者更好的是,如何使它起作用?下面是示例代码和编译器错误。
资料来源:Fo.C1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <iostream> using namespace std; template<typename X, typename D> struct foo; template<typename X> struct bar : foo<X,bar<X> > { X evaluate() { return static_cast<X>( 5.3 ); } }; template<typename X> struct baz : foo<X,baz<X> > { X evaluate() { return static_cast<X>("elk" ); } }; template<typename X, typename D> struct foo : D { X operator() () { return static_cast<D*>(this)->evaluate(); } }; template<typename X, typename D> void print_foo( foo<X,D> xyzzx ) { cout <<"Foo is" << xyzzx() <<" "; } int main() { bar<double> br; baz<const char*> bz; print_foo( br ); print_foo( bz ); return 0; } |
编译程序错误
1 2 3 4 5 6 7 8 9 10 | foo.C: In instantiation of ‘foo<double, bar<double> >’: foo.C:8: instantiated from ‘bar<double>’ foo.C:30: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct bar<double>’ foo.C:8: error: declaration of ‘struct bar<double>’ foo.C: In instantiation of ‘foo<const char*, baz<const char*> >’: foo.C:13: instantiated from ‘baz<const char*>’ foo.C:31: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct baz<const char*>’ foo.C:13: error: declaration of ‘struct baz<const char*>’ |
CRTP的思想是让一个基类知道它的导数是什么类型,而不是让基类从它的导数派生出来。否则,您将出现以下情况:
Derived 来源于Base ,其中- 源自
Derived ,其中 - 来源于
Base ,其中 - …
改为使用以下内容:
1 2 | template<typename X, typename D> struct foo // : D // ... ^ remove that |