2016-10-04 28 views
1

我試圖超載運算符< <僅打印STL容器的每兩個元素。但是,我在編譯過程中有一個錯誤:錯誤:'e'不是類,名稱空間或枚舉

error: 'e' is not a class, namespace, or enumeration 

這裏是我的代碼:

#include <iostream> 
#include <vector> 

template<typename T> 
std::ostream& operator<<(std::ostream &out, T const &e){ 
    for(e::iterator it = e.begin(); it != e.end(); it = it + 2){ 
     out << *it << " "; 
    } 
    return out; 
} 

int main(){ 
    std::vector<int> v; 
    for(int i= 0; i < 10; i++){ 
     v.push_back(i); 
    } 

    std::cout << v; 
    return 0; 
} 
+0

通過'T'更換Ë:: iterator' :: iterator' – purplepsycho

+0

使用'汽車&& it' – 101010

回答

4

你有兩個問題在這裏。

一個是e::iterator。您無法通過對象訪問成員類型,您需要使用該類型。相反,你應該只使用auto it = e.begin()。如果您不能使用C++ 11,那麼你就需要使用

typename T::const_iterator it = e.begin() 

typename需要因爲這個名字是依賴於一個模板參數,並且需要,而不是僅僅iteratorconst_iterator,因爲該參數標記爲const

然而,你的更嚴重的錯誤是首先使這個過載。

template<typename T> 
std::ostream& operator<<(std::ostream &out, T const &e){ 

這聲明爲std::ostream輸出的過載爲任何類型。這肯定會讓你頭疼,果然,如果解決的第一個錯誤,你想輸出" "時得到一個模棱兩可的函數調用錯誤:

main.cpp:7:20: error: use of overloaded operator '<<' is ambiguous (with operand types '__ostream_type' (aka 'basic_ostream<char, std::char_traits<char> >') and 'const char [2]') 
     out << *it << " "; 
     ~~~~~~~~~~^~~~ 

如果你真的想這個工作每個標準庫容器,我想你會檢查是否存在類似T::iterator的東西,並且只有在你的超負荷被啓用的情況下才會這樣。事情是這樣的:

template<typename T, typename = typename T::iterator> 
std::ostream& operator<<(std::ostream &out, T const &e){ 
    for(auto it = e.begin(); it != e.end(); it = it + 2){ 
     out << *it << " "; 
    } 
    return out; 
} 

Live demo

相關問題