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

14,609

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

Solution 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;
}
Share:
14,609
Joey
Author by

Joey

Updated on June 04, 2022

Comments

  • Joey
    Joey almost 2 years

    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.

    • visual_learner
      visual_learner over 12 years
      I'm not totally convinced that you've provided us with enough code to solve this problem, but the info you have given us leads me to ask: Why does operator<<(std::ostream&, const T&) need access to BinTree<T>'s internals if it doesn't ever use them (or BinTree<T>)?
  • AnT stands with Russia
    AnT stands with Russia about 5 years
    Um... Where exactly did you find that such function in the standard library?