2012-10-02 37 views
1

問題如下:以下測試會引發大量編譯器錯誤。試圖從模板函數返回一個向量會引發編譯錯誤。

#include <vector> 
using namespace std; 

template<class T> 
class test{ 
    vector<T> vec; 
public: 
    vector<T>::iterator begin(); 

}; 

template<class T> 
vector<T>::iterator test<T>::begin(){ 
    return vec.begin(); 
} 

int main(){ 

    test<float> testing; 
    testing.begin(); 

} 

一些編譯器錯誤:

test.cpp(8): warning C4346: 'std::vector<T>::iterator' : dependent name is not a type 
test.cpp(8): error C2146: syntax error : missing ';' before identifier 'begin' 
test.cpp(13): error C2143: syntax error : missing ';' before 'test<T>::begin' 

但是,如果換出的發言權模板vector<T>vector<float>它編譯就好了。例如:

template<class T> 
class test{ 
    vector<T> vec; 
public: 
    vector<float>::iterator begin(); 

}; 

template<class T> 
vector<float>::iterator test<T>::begin(){ 
    return vec.begin(); 
} 

任何想法爲什麼?

回答

2

您需要在兩個地方添加typename

typename vector<T>::iterator begin(); 

typename vector<T>::iterator test<T>::begin() 

通過添加typename,你告訴編譯器如何解析的代碼。基本上,通過添加typename,您告訴編譯器將聲明解析爲類型。

請仔細閱讀Where and why do I have to put the 「template」 and 「typename」 keywords?進行深入的解釋。

1

您需要使用typename關鍵字來區分vector<T>::iterator指的是一個範圍的類型,而不是範圍的數據或函數成員:

template<class T> 
class test{ 
    vector<T> vec; 
public: 
    typename vector<T>::iterator begin(); 

}; 

template<class T> 
typename vector<T>::iterator test<T>::begin(){ 
    return vec.begin(); 
} 
+0

它*是*成員 - 只是成員*類型*,不是成員變量。 –

+0

@KerrekSB:更正,謝謝。 – jxh

-2

在C++中的模板類,模板的成員函數必須有自己的身體在類中定義,因爲模板參數不存在於類之外。最後兩個錯誤看起來像編譯器在陌生的上下文導致錯誤解釋完全有效的語法時產生的結果。嘗試在類中移動函數體。

+0

這是不正確的。在實例化模板的地方,模板的定義必須是可見的,但它不一定要在類聲明中。 – jmk

+0

對不起。我正在考慮將模板分成多個文件。我的錯。 – ValekHalfHeart

+0

不用擔心,只是想澄清,所以沒有人會太困惑。儘管如此,你可能想要編輯/刪除你的答案。 – jmk

相關問題