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.

1
  • 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<T>'s internals if it doesn't ever use them (or BinTree<T>)? Commented Oct 16, 2011 at 5:45

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Um... Where exactly did you find that such function in the standard library?
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;
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.