The following will not compile for me. I have no ideas ... Any help?
template<> inline std::ostream& operator<< <const std::map<std::string, std::string> > (std::ostream& stream, const std::map<std::string, std::string>& some_map) { return stream; }
g ++ gives me the following error:
error: expected initializer to '<' token
Edit: 1 Good, since everyone is telling me to overload, let me give you an example that does not make sense to overload. What if I have this:
template <typename T> inline std::ostream& operator<<(std::ostream& stream, const T& something) { stream << something.toString(); return stream; } class Foo { public: Foo(std::string s) { name = s; } std::string toString() const { return name; } private: std::string name; }; class Bar { public: Bar(int i) { val = i; } std::string toString() const { std::ostringstream stream; stream << val; return stream.str(); } private: int val; }; int main(int, char**) { Foo foo("hey"); Bar bar(2); std::cout << foo << std::endl; std::cout << bar << std::endl; return 0; }
Now that won't work either.
I just want to avoid overloading the <<<operator over and over again using the pattern as above. It seems to be possible. I would like to know if this is so, and if so, how?
In this case, overloading both Foo and Bar to do the same would be a waste, so I try to avoid it.
Edit: 2 Well, it seems like they misunderstood me. Here is another attempt to clarify:
template <typename T> std::ostream& operator<<(ostream& stream, const T& t) { for(typename T::const_iterator i = t.begin(), end = t.end(); i != end; ++i) { stream << *i; } return stream; } int main(int, char**) { set<int> foo; list<string> bar; vector<double> baz; cout << foo << " " bar << " " << baz << endl; };
The code above will not work for you. Complains of ambiguity. But this seems like the best solution for printing containers. If I did this with overload, I would have to write a version of the <<operator for each container / data combination, which would lead to ridiculous code duplication.