2010-10-22 52 views
2

我試圖做一個漂亮的打印機進行的std :: vector的什麼的...雙打,我自己的自定義類...任何有friend std::ostream& operator<<「預期;在此之前......」用模板功能打印的std ::矢量<Whatever>

但是,試圖編譯以下功能時:

template <typename T> 
std::ostream& operator<<(std::ostream& os, std::vector<T> const& list) { 
    std::vector<T>::const_iterator i = list.begin(); 

    if (i == list.end()) { 
    os << "[ ]"; 
    return os; 
    } 

    os << "[ " << *i << "\n"; 

    ++i; 
    for (; i != list.end(); ++i) { 
    os << ", " << *i << "\n"; 
    } 

    os << "]"; 
    return os; 
} 

第三行給出了一個編譯錯誤,error: expected ';' before 'i'

我真的不知道是什麼導致這一點,但我懷疑我濫用模板。任何幫助,將不勝感激!

回答

6

編譯器不知道你想,因爲模板表達式是基於模板參數聲明i作爲變量。這就是爲什麼關鍵字typename是。試試這個:

typename std::vector<T>::const_iterator i = list.begin();