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:
And I want to add a space string in each value, 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.
Aucun commentaire:
Enregistrer un commentaire