How to write a streaming 'operator<<' that can take arbitary containers (of type 'X')?
Posted
by
Drew Dormann
on Stack Overflow
See other posts from Stack Overflow
or by Drew Dormann
Published on 2012-12-05T13:51:39Z
Indexed on
2012/12/11
23:04 UTC
Read the original article
Hit count: 593
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.)
© Stack Overflow or respective owner