通用打印功能 [英] A generic print function

查看:144
本文介绍了通用打印功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有一本好的C ++书籍,而且google pull up没有什么用处。

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?

我在哪里可以查看运算符<<() c.begin()

Where can I go to look at the operator<<() so that I can overload it?

$ c>, c.end() ...但是对于输出,你需要一个place ostream_iterator 。这似乎有点不对称。

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


推荐答案

我会给它一个镜头:


技术上,是操作符<<知道如何写它,使<<

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.


对于输入,还需要一个开始和结束placec.begin(),c.end但对于输出,你需要一个地方ostream_iterator。这看起来有点不对称。

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.

把这作为一个问题...

这就是 std :: copy()定义:它需要一个输入范围(由begin和end迭代器定义),以及一个输出迭代器,用于写入。它假设,无论它写在哪里,有足够的空间。 (如果你接受一个输出流操作符,总有足够的空间。)

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.)

你可能想让自己一本好的C ++书

这篇关于通用打印功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆