2011-10-16 84 views
3

我試圖重載< <運營商,但我得到了以下錯誤:重載運算符<<(模板)時,如何解決「模糊超載」錯誤?

error: ambiguous overload for 'operator<<' in 'std::cout << "Test "'

5個十億類似於其他錯誤..Followed:

c:\mingw\bin../lib/gcc/mingw32/4.5.2/include/c++/ostream:165:7: note: candidates are: ...

這來了,因爲我」 m在我的main.cpp文件中使用cout。

這裏是我的代碼:

在BinTree.h:

template <typename T> 
    class BinTree{ 
    ... 
    friend std::ostream& operator<< <>(std::ostream&, const T&); 

在BinTree.cpp:

template <typename T> 
    std::ostream& operator<< (std:: ostream& o, const T& value){ 
     return o << value; 
    } 

預先感謝任何幫助,您可以給。

+1

我不完全相信你已經爲我們提供了足夠的代碼來解決這個問題,但你_have_給我們的信息使我問:爲什麼'operator <<(std :: ostream&,const T&)'需要訪問'BinTree '的內部,如果它沒有使用它們(或BinTree ')? –

回答

4

您的函數與已定義的函數具有相同的簽名。這就是爲什麼編譯器呻吟無聊的過載。你的函數試圖定義一個函數把所有東西都流到一個ostream。該功能已經存在於標準庫中。

template <typename T> 
std::ostream& operator<< (std:: ostream& o, const T& value){ 
    return o << value; 
} 

你可能想要做的是編寫一個函數來定義BinTree如何流式傳輸(到任何事物)。請注意,流類型是模板化的。因此,如果將調用鏈接到流操作符,則會傳輸具體類型。

template <typename T, typename U> 
T& operator<< (T& o, const BinTree<U>& value){ 
    //Stream all the nodes in your tree.... 
    return o; 
} 
0

郵政更多的代碼,到那時看到這部分:

template <typename T> 
std::ostream& operator<< (std:: ostream& o, const T& value){ 
    return o << value; 
} 

這是在做什麼,但自稱。這是遞歸調用。 operator<<定義爲T類型的輸出值,當您編寫o<<value時,它會自行調用,因爲value的類型爲T。第二,由於這是函數模板,因此如果您希望您的代碼通過包含.h文件工作,則應在.h文件中提供定義,而不是在.cpp文件中提供該定義。

2

你的意思..

template<class T> 
ostream& operator<<(ostream& os, const BinTree<T>& v){ 
    typename BinTree<T>::iterator it; 
    for(it = v.begin(); it != v.end(); ++it){ 
       os << *it << endl; 
    } 
    return os; 
}