I want to print values of STL types like std::maps, for example:
int main()
{
std::map<int, std::vector<int>> t = {{1, {2, 3}}, {4, {5}}};
std::cout << t << std::endl;
return 0;
}
This fails because operator<< isn't defined for these types.
If I try to define it myself, I have to also forward declare my definitions, otherwise the compilation fails with:
error: call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup
o << sep << "{" << x.first << ", " << x.second << "}";
...
note: 'operator<<' should be declared prior to the call site std::ostream& operator<< (std::ostream& o, const std::vector<T>& vec)
That is unfortunate because having to forward declare the methods would require using two includes for each type (forward declarations first and then implementations).
- Is there a way to define
operator<<for templated types in a modular way? - Is this difficulty the reasoning behind why
operator<<isn't available for STL types out of the box?
Reference: A working implementation with forward declarations