How to write a streaming 'operator<<' that can take arbitary containers (of type 'X')?
- by Drew Dormann
I have a C++ class "X" which would have special meaning if a container of them were to be sent to a std::ostream.
I originally implemented it specifically for std::vector<X>:
std::ostream& operator << ( std::ostream &os, const std::vector<X> &c )
{
// The specialized logic here expects c to be a "container" in simple
// terms - only that c.begin() and c.end() return input iterators to X
}
If I wanted to support std::ostream << std::deque<X> or std::ostream << std::set<X> or any similar container type, the only solution I know of is to copy-paste the entire function and change only the function signature!
Is there a way to generically code operator << ( std::ostream &, const Container & )?
("Container" here would be any type that satisfies the commented description above.)