How do I fix “ambiguous overload” error when overloading operator<< (templated)?

假如想象 提交于 2019-12-12 13:34:26

问题


I am trying to overload the << operator, but I get the following error:

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

..Followed by 5 billion other errors similar to:

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

This comes up because I'm using cout in my main.cpp file.

Here is my code:

In BinTree.h:

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

In BinTree.cpp:

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

Thanks in advance for any help you can give.


回答1:


Your function has the same signature than the one already defined. This is why the compiler moans about ambigous overload. Your function tries to define a function to stream everything to a ostream. This function already exists in the standards library.

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

What you perhaps want to do is write a function that defines how a BinTree is streamed (to everything). Please note that the stream type is templated. So if you chain the calls to the stream operator it streams the concrete type.

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



回答2:


Did you mean..

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;
}



回答3:


Post more code, till then see this part:

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

This is doing nothing but calling itself. It is recursive call. The operator<< is defined to output value of type T, and when you write o<<value, it calls itself, as the type of value is T.

Second, since this is function-template, the definition should be provided in the .h file, not in .cpp file if you expect your code working by including .h file.



来源:https://stackoverflow.com/questions/7782577/how-do-i-fix-ambiguous-overload-error-when-overloading-operator-templated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!