3

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.

iammilind
  • 68,093
  • 33
  • 169
  • 336
Joey
  • 41
  • 1
  • 2
  • 4
  • 1
    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`'s internals if it doesn't ever use them (or `BinTree`)? – Chris Lutz Oct 16 '11 at 05:45

3 Answers3

6

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;
}
David Feurle
  • 2,687
  • 22
  • 38
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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851