简体   繁体   English

boost :: function对象容器上的STL算法

[英]STL algorithms on containers of boost::function objects

I have the following code that uses a for loop and I would like to use transform, or at least for_each instead, but I can't see how. 我有以下使用for循环的代码,但我想使用transform,或者至少要使用for_each,但是我看不到如何。

typedef std::list<boost::function<void(void) > CallbackList;
CallbackList callbacks_;

//...
for(OptionsMap::const_iterator itr = options.begin(); itr != options.end(); ++itr)
{
   callbacks_.push_back(boost::bind(&ClassOutput::write_option_,this,*itr));
}

Later on in the code, I actually want to call this collection of nullary function objects. 在代码的稍后部分,我实际上要调用此空函数对象的集合。 I'm using a for loop here as well, and it seems like I should be able to use for_each somehow. 我也在这里使用for循环,似乎我应该能够以某种方式使用for_each。

for(CallbackList::iterator itr = callbacks_.begin(); itr != callbacks_.end(); ++itr)
{    
  (*itr)();
}

I managed to figure out part 2: 我设法弄清楚了第2部分:

typedef boost::function<void(void)> NullaryFunc;
for_each(callbacks_.begin(),callbacks_.end(),boost::bind(&NullaryFunc::operator(),_1));

To do all this in a single transform call, you I think you need to call bind on itself, because you need a functor which calls boost:bind. 要在单个转换调用中完成所有这些操作,我想您需要对自身调用bind,因为您需要一个调用boost:bind的函子。 That's something I've never attempted. 这是我从未尝试过的事情。 Would you settle for something like this (untested)? 您会满足这样的条件(未经测试)吗?

struct GetFunc {
    ClassOutput *obj;
    boost::function<void(void) > operator()(const OptionsMap::value_type &v) {
        return boost::bind(&ClassOutput::write_option_, obj, v);
    }
    GetFunc(ClassOutput *obj) : obj(obj) {}
};

transform(options.begin(), options.end(), back_inserter(callbacks_), GetFunc(this));

In C++0x you can use a lambda instead of the functor class: 在C ++ 0x中,可以使用lambda代替functor类:

transform(options.begin(), options.end(), back_inserter(callbacks_), 
    [this](const OptionsMap::value_type &v) {
        return boost::bind(&ClassOutput::write_option_, this, v);
    }
);

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

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