丢弃需要输出迭代器的函数的输出 [英] Discarding the output of a function that needs an output iterator

查看:125
本文介绍了丢弃需要输出迭代器的函数的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在C ++中有一个模板函数,它有一些有用的工作,但也通过输出迭代器输出值序列。现在假设该序列的值有时是有趣的,但在其他的没有用。在STL中是否有一个即用型迭代器类,可以实例化并传递给函数,并忽略函数尝试分配给输出迭代器的任何值?换句话说,将所有数据发送到/ dev / null?

Suppose there´s a template function in C++ that does some useful work but also outputs a sequence of values via an output iterator. Now suppose that that sequence of values sometimes is interesting, but at others is not useful. Is there a ready-to-use iterator class in the STL that can be instantiated and passed to the function and will ignore any values the function tries to assign to the output iterator? To put in another way, send all data to /dev/null?

推荐答案

STL不提供这样的迭代器。但你可以自己编写代码(测试代码):

The STL does not provide such an iterator. But you could code it yourself (tested that code):

struct null_output_iterator : 
    std::iterator< std::output_iterator_tag,
                   null_output_iterator > {
    /* no-op assignment */
    template<typename T>
    void operator=(T const&) { }

    null_output_iterator & operator++() { 
        return *this; 
    }

    null_output_iterator operator++(int) { 
        return *this;
    }

    null_output_iterator & operator*() { return *this; }
};

使用自身作为运算符的结果不需要任何数据* 。在输出迭代器的要求中不使用 * it = x; 的结果,所以我们可以给它一个返回类型 void

It doesn't need any data by using itself as the result of operator*. The result of *it = x; is not used in the output iterator requirements, so we can give it a return type of void.

编辑:让我们进入运算符* 工程。标准在 24.1.2 / 1 中说明了在这两种情况下输出迭代器的要求:

Let's go into how this operator* works. The Standard says in 24.1.2/1 about the requirements of an output iterator that in both these cases:

*it = t;
*it++ = t;

不使用这些表达式的结果。这是什么使这项工作:

That the result of those expressions is not used. That's what makes this work:

null_output_iterator it;
*it; // returns a null_output_iterator& per definition of the `operator*`.
*it = some_value; // returns void per definition of the templated `operator=`. 

现在我们不需要在运算符中返回任何数据* :我们只是使用迭代器本身。请注意,模板化运算符=不覆盖内置拷贝分配运算符。仍然提供。

Now we don't need to have any data that we return in operator*: We just use the iterator itself. Note that the templated operator= does not overwrite the builtin copy assignment operator. It's still provided.

这篇关于丢弃需要输出迭代器的函数的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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