user656925
user656925

Reputation:

A generic print function

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; 
}

Upvotes: 0

Views: 338

Answers (1)

sbi
sbi

Reputation: 224099

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.

Upvotes: 1

Related Questions