通用打印功能

发布于 2024-12-12 08:07:32 字数 625 浏览 0 评论 0原文

我手头没有一本好的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谎言 2024-12-19 08:07:32

这很模糊,但我会尝试一下:

从技术上讲,operator<<() 的原型是预定义的,作者如何知道如何编写它以便 <<是否已重载以输出容器值?

我可以去哪里查看运算符<<()以便我可以重载它?

您可以为所有尚未重载的用户定义类型重载运算符。有关详细信息,请参阅此处

此外,对于输入,您需要一个开始和结束“位置”c.begin()、c.end()...但对于输出,您需要一个“位置”ostream_iterator。这看起来有点不对称。

以此作为一个问题...
这就是 std::copy() 的定义方式:它需要一个输入范围(由开始和结束迭代器定义)和一个用于写入位置的输出迭代器。它假设无论写入到哪里,都有足够的空间。 (如果您采用输出流运算符,则总是有足够的空间。)

您可能希望自己 一本不错的 C++ 书

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文