I'm trying to overload the << operator so I can do, for example,
list<string> string_list = ...;
vector<double> double_vector = ...;
set<list<int>> int_list_set = ...;
cout << string_list << double_vector << int_list_set << endl;
Another user of this site, Chris Redford, posted some helpful code for doing this with vectors at How to print out the contents of a vector? . I've attempted to adapt his code to work with other types of collection as follows:
template <template <typename...> class collection, typename T>
std::ostream& operator<<(std::ostream& out, const collection<T>& c) {
out << "[ ";
out << *c.begin();
for(auto it=next(c.begin(),1); it!=c.end(); ++it) {
out << " , ";
out << *it;
}
out << " ]";
return out;
}
Obviously I'm a noob when it comes to writing templates, so any tips for reading materials would be welcome. Hopefully it is clear that I'd like this to work for anything that can do .begin() and .end(). When compiling this with
int main(int argc, char **argv) {
list<string> words;
words.push_back("hello");
words.push_back("world");
cout << words << endl;
}
, I get a compiler error saying "ambiguous overload for 'operator<<'" and a bunch of gobbledy goop I don't understand. I think gcc might be trying to redefine what << means for std::string, but I'm not sure. Ideally, I'd like to tell the compiler not to try to redefine this operation for types for which it is already defined. I'm also using -std=C++14 so I'm open to clever use of auto. Any suggestions?
Edit: corrected bad use of T... in original question.