问题
I don't have a good C++ book on hand and google pulls ups nothing useful.
How does this work? Conceptually what is going on here? Technically, is the prototype for operator<<() predefined, how did the writer of this know how to write it so that << is overloaded to output Container values?
Where can I go to look at the operator<<()
so that I can overload it?
Also for an input you need a start and an end "place" c.begin()
, c.end()
...but for output you need one "place" ostream_iterator
. This seems a bit asymmetrical.
template <typename Container>
std::ostream& operator<<(std::ostream& os, const Container& c)
{
std::copy(c.begin(), c.end(),
std::ostream_iterator<typename Container::value_type>(os, " "));
return os;
}
回答1:
This is pretty vague, but I'll give it a shot:
Technically, is the prototype for operator<<() predefined, how did the writer of this know how to write it so that << is overloaded to output Container values?
Where can I go to look at the operator<<() so that I can overload it?
You can overload operators for all user-defined types for which they are not already overloaded. See here for more info on this.
Also for an input you need a start and an end "place" c.begin(), c.end()...but for output you need one "place" ostream_iterator. This seems a bit asymmetrical.
Taking this as a question...
That's just how std::copy()
is defined: It takes an input range (defined by begin and end iterators), and an output iterator for where to write. It assumes that, wherever it writes to, there's enough room. (If you take an output stream operator, there's always enough room.)
You might want to get yourself a good C++ book.
来源:https://stackoverflow.com/questions/7942174/a-generic-print-function