2012-07-23 148 views
0

Possible Duplicate:
「Inherited」 types using CRTP and typedef爲什麼這個CRTP不能編譯?

template<typename T> 
struct A { 
    typename T::Sub s; 
}; 

struct B : A<B> { 
    struct Sub {}; 
}; 

鏘報告這種錯誤:

todo.cc:3:15: error: no type named 'Sub' in 'B' 
    typename T::Sub s; 
    ~~~~~~~~~~~~^~~ 
todo.cc:6:12: note: in instantiation of template class 'A<B>' requested here 
struct B : A<B> { 
     ^

我怎樣才能得到這個工作?

+2

當'B'包含的定義如何'B'從'A'繼承'A'中需要的東西? – chrisaycock 2012-07-23 17:06:24

回答

2

B是一個不完整的類,它在請求實例化A<B>的點上。

這意味着您只能在A的模板方法中參考B,因爲這些方法的實例化將延遲到B完成。

1

由於BA<B>繼承,A<B>必須被構造之前B是。

由於您使用的是CRTP,因此在構建A<B>時,這意味着B是不完整的類。由於這個原因,編譯器無法確定B是否有成員字段Sub,因此編譯失敗。

需要注意的是,這一次,GCC給出一個更有意義的錯誤:

$ cat crtp.cpp

template<typename T> 
struct A { 
     typename T::Sub s; 
}; 

struct B : A<B> { 
     struct Sub {}; 
}; 

$ g++ -c crtp.cpp -o crtp.o

crtp.cpp: In instantiation of ‘A<B>’: 
crtp.cpp:6:17: instantiated from here 
crtp.cpp:3:21: error: invalid use of incomplete type ‘struct B’ 
crtp.cpp:6:8: error: forward declaration of ‘struct B’