【问题标题】:STL algorithms on containers of boost::function objectsboost::function 对象容器上的 STL 算法
【发布时间】:2010-01-04 18:21:52
【问题描述】:

我有以下使用 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));
}

在后面的代码中,我实际上想调用这个空函数对象的集合。我在这里也使用了 for 循环,看来我应该能够以某种方式使用 for_each。

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

【问题讨论】:

    标签: c++ stl boost-bind boost-function


    【解决方案1】:

    我设法弄清楚了第 2 部分:

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

    【讨论】:

      【解决方案2】:

      要在单个转换调用中完成所有这些,我认为您需要对其自身调用 bind,因为您需要一个调用 boost:bind 的函子。这是我从未尝试过的事情。你会接受这样的事情吗(未经测试)?

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

      在 C++0x 中,您可以使用 lambda 代替仿函数类:

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

      【讨论】:

      • 只需一项更改即可。 operator() 的参数应该是 OptionsMap::value_type。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2014-06-17
      • 2013-08-12
      • 2012-03-17
      相关资源
      最近更新 更多