2012-09-24 43 views
2

可能重複:
Where and why do I have to put the 「template」 and 「typename」 keywords?如何爲泛型類型的向量聲明一個迭代器?

我聲明爲是一個通用類型的矢量的迭代器的問題。 代碼如下:

template <class T> void print(const vector<T>& V) 
    { 
     vector<T>::const_iterator i; 
    } 

下面返回預期的誤差;於我之前'。 如果我特別說明,將不會有錯誤vector<int>::const_iterator i;

有沒有辦法解決這個問題?

+0

'類型名稱矢量 ::爲const_iterator我;' – hmjd

回答

3

const_iterator是在此上下文中的從屬名稱,因爲它取決於T。除非您明確使用關鍵字typename來限定它,否則不會假定其類型。

template <class T> void print(const vector<T>& V) 
{ 
    typename vector<T>::const_iterator i; 
} 
1

你需要這樣做:

template <class T> void print(const vector<T>& V) 
    { 
     //T is a dependant type so needs typename 
     typename vector<T>::const_iterator i; 
    }