[英]C++ Template: 'is not derived from type'
為什么這段代碼無效?
#include <vector>
template <typename T>
class A {
public:
A() { v.clear(); }
std::vector<A<T> *>::const_iterator begin() {
return v.begin();
}
private:
std::vector<A<T> *> v;
};
GCC報告以下錯誤:
test.cpp:8: error: type 'std::vector<A<T>*, std::allocator<A<T>*> >' is not derived from type 'A<T>'
test.cpp:8: error: expected ';' before 'begin'
test.cpp:12: error: expected `;' before 'private'
怎么了? 怎么解決?
在這一行中,您缺少typename
關鍵字:
std::vector<A<T> *>::const_iterator begin(){
你需要:
typename std::vector<A<T> *>::const_iterator begin(){
這是因為std::vector<A<T> *>
依賴於類模板( A
)的模板參數( T
)。 為了能夠正確解析模板而不必對任何其他模板的可能特化做出任何假設,語言規則要求您使用typename
關鍵字指示哪些從屬名稱表示類型。
你需要添加typename作為彼此依賴的類型,編譯器無法弄清楚它是否真的是一個類型。
但是,在gcc 4.5.0上我得到一個更簡潔的錯誤消息:
test.cc:8:3: error: need 'typename' before 'std::vector<A<T>*>::const_iterator' because 'std::vector<A<T>*>' is a dependent scope
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.