通用打印功能
我手头没有一本好的 C++ 书,谷歌也没有找到任何有用的东西。
这是如何运作的?从概念上讲,这里发生了什么?从技术上讲,operator<<() 的原型是预定义的,作者如何知道如何编写它以便 <<是否已重载以输出 Container 值?
我可以在哪里查看operator<<()
以便我可以重载它?
另外,对于输入,您需要一个开始和结束“位置”c.begin()
、c.end()
...但对于输出,您需要一个“位置” “ostream_iterator
。这看起来有点不对称。
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这很模糊,但我会尝试一下:
您可以为所有尚未重载的用户定义类型重载运算符。有关详细信息,请参阅此处。
以此作为一个问题...
这就是 std::copy() 的定义方式:它需要一个输入范围(由开始和结束迭代器定义)和一个用于写入位置的输出迭代器。它假设无论写入到哪里,都有足够的空间。 (如果您采用输出流运算符,则总是有足够的空间。)
您可能希望自己 一本不错的 C++ 书。
This is pretty vague, but I'll give it a shot:
You can overload operators for all user-defined types for which they are not already overloaded. See here for more info on this.
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.