开发者

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

开发者 https://www.devze.com 2023-04-13 02:28 出处:网络
I am trying to overload the << operator, but I get the following error: error: ambiguous overload for \'operator<<\' in \'std::cout << \"Test \"\'

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 <<开发者_如何学JAVA value;
    }

Thanks in advance for any help you can give.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号