2

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 << " ";
    }
iammilind
  • 68,093
  • 33
  • 169
  • 336

2 Answers2

4

(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.

servn
  • 3,049
  • 14
  • 8
  • Yes right, it is erroneous to write something like that also if some compiler may allowed it in the past, as i was thinking at the beginning. – Salvatore Previti Oct 30 '11 at 02:45
1

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);
Salvatore Previti
  • 8,956
  • 31
  • 37
  • This was given as an answer on SO here http://stackoverflow.com/questions/7855941/necessity-of-writing-print-functions-for-containers –  Oct 30 '11 at 02:25