A generic print function

谁都会走 提交于 2019-12-13 06:49:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!