Reputation:
Ambiguous overload for operator<<()
is called when I add the overload function below
template <typename Container> ostream& operator<<(ostream& os, const Container& c)
{
copy(c.begin(), c.end(), ostream_iterator<typename Container::value_type>(os, " "));
return os;
}
the error is called on this function where it uses the <<
.
void print_list(const list<int>& list_int)
{
for (list<int>::const_iterator it = list_int.begin(); it != list_int.end(); it++) cout << *it << " ";
}
Upvotes: 2
Views: 90
Reputation: 3069
(For reference, if anyone else is looking: http://ideone.com/YlX7q )
Your definition of operator<< can be instantiated as ::operator<<<int>(std::ostream&, const int&)
; this is ambigious with std::operator<<(std::ostream&, int)
. Calling the name of the type Container doesn't mean it is a container; overload resolution is done before the definition is instantiated.
Upvotes: 4
Reputation: 9070
Yes of course this cannot work. You are introducing a templated overload, and the compiler don't know anymore what to use when you use that operator. Simply you cannot do that.
You can do something like this:
template<class T>
friend ostream& operator<<(ostream& os, const MyClass<T>& r);
but you cannot do
template<class T>
friend ostream& operator<<(ostream& os, const T& r);
Upvotes: 1