C++ print template container error (error: ambiguous overload for 'operator<<') understanding?

  • A+
Category:Languages

I want to write template function which can print container like std::vector, std::list.

Below is my function, just overload <<.

template<typename Container> std::ostream& operator<<(std::ostream& out, const Container& c){     for(auto item:c){         out<<item;     }     return out; } 

Test code as below:

int main(){     std::vector<int> iVec{5, 9, 1, 4, 6};     std::cout<<iVec<<std::endl;     return 0; } 

ouput:

59146 

And I want to add a space string in each value(output like 5 9 1 4 6), so I change the function to:

template<typename Container> std::ostream& operator<<(std::ostream& out, const Container& c){     for(auto item:c){         out<<item<<" ";     }     return out; } 

Then it get error:

merror: ambiguous overload for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const char [2]')          out<<item<<" "; 

I know << can output common type like.

int a = 0; double f = 0.3; std::string s = "123"; std::cout<<a<<f<<s<<std::endl; 

So Why get the above error ? And is there any way to solve it?

I have see this question Ambiguous overload for ‘operator<<’ in ‘std::cout << but I still can't understand clearly.

All code:

#include <iostream> #include <vector>  template<typename Container> std::ostream& operator<<(std::ostream& out, const Container& c){     for(auto item:c){         out<<item;         // out<<item<<" "; // error     }     return out; }  int main(){     std::vector<int> iVec{5, 9, 1, 4, 6};     std::cout<<iVec<<std::endl;     return 0; } 

 


Declaring template<typename Container> could be dangerous as this template includes 'all' variable types int, char etc. Due to this compiler does not know which operator<< to use.

In order to take only container type variables use template of templates. Here is working code for you

template<typename T, template <typename, typename> class Container> std::ostream& operator<<(std::ostream& out, const Container<T, std::allocator<T>>& c) {     for (auto item : c) {         out << item << " ";     }      return out; }  int main() {     cout << "Hello world" << endl;     int arr[] = { 0,3,6,7 };     vector<int> v(arr, arr+4);     cout << v << endl;     return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: