简体   繁体   English

Boost:功能输出迭代器,重塑车轮

[英]Boost: Function Output Iterator, reinventing the wheel

Normally someone would just go and grab Boost's Function Output Iterator but I'm not allowed to use Boost at work. 通常有人会去抓住Boost的Function Output Iterator,但是我不允许在工作中使用Boost。 That said, I just want to use the copy function to traverse a collection, call a function on each item, take the output of that function, and finally push_back it onto another collection. 也就是说,我只想使用copy函数遍历一个集合,在每个项目上调用一个函数,获取该函数的输出,最后将其push_back到另一个集合上。 I've written some code: 我写了一些代码:

#include <iterator>
using std::iterator;
using std::output_iterator_tag;

template<typename Container, typename Function>
struct Back_Transform_Iterator : public iterator<output_iterator_tag,void,void,void,void>{
    explicit Back_Transform_Iterator(Container &_container, const Function &_function) 
        : m_Container(_container),
        m_Function(_function){}

    Back_Transform_Iterator<Container,Function>& operator= (const typename Function::argument_type &value){ 
      m_Container.push_back( m_Function( value ) );

      return *this; 
    }

    Back_Transform_Iterator<Container,Function>& operator* (){ return *this; }
    Back_Transform_Iterator<Container,Function>& operator++ (){ return *this; }
    Back_Transform_Iterator<Container,Function> operator++ (int){ return *this; }

    typedef Container container_type;

private:
    Container   &m_Container;
    Function    m_Function;
};

template<typename C, typename F>
Back_Transform_Iterator<C,F> back_transform_inserter(C &_container, F &_unary_function){
    return Back_Transform_Iterator<C,F>( _container, _unary_function );
}

but... I'm getting compilation problems. 但是...我遇到了编译问题。 Fairly certain it's to do with the operator*() call. 可以肯定的是,它与operator*()调用有关。 I have no idea how to effectively dereference the container's objects so that they object the function's effects. 我不知道如何有效地取消引用容器的对象,以便它们反对函数的效果。 Error: 错误:

error C2582: 'operator =' function is unavailable in 'Back_Transform_Iterator<Container,Function>'

the items I'm iterating over are not mutable. 我要遍历的项目是不可变的。 Anyone know how to tackle this issue? 有人知道如何解决这个问题吗?

You can use transform instead: 您可以改用transform

transform(src.begin(), src.end(), back_inserter(container), func);

Note that const applied on a reference type is a no-op. 注意,应用于引用类型的const是no-op。 So if argument_type is T& , then saying const argument_type does not yield back const T& but T& again. 因此,如果argument_typeT& ,则说const argument_type不会再返回const T&而是再次返回T& So if your source items are constant you would try to bind them to the non-const reference parameter of operator= in case that argument_type is a reference: 因此,如果您的源项目是常量,则在argument_type是引用的情况下,您将尝试将其绑定到operator=的非常量引用参数:

typedef int &intr;
const intr& a = 0; // fails - "const" is ignored!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM