1

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

コードの後半で、このnullary関数オブジェクトのコレクションを実際に呼び出したいと思います。ここでもforループを使用していますが、どういうわけかfor_eachを使用できるはずです。

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

2 に答える 2

3

私はなんとかパート2を理解することができました。

typedef boost::function<void(void)> NullaryFunc;
for_each(callbacks_.begin(),callbacks_.end(),boost::bind(&NullaryFunc::operator(),_1));
于 2010-01-04T18:33:32.507 に答える
2

これらすべてを1回の変換呼び出しで行うには、boost:bindを呼び出すファンクターが必要なため、それ自体で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では、ファンクタークラスの代わりにラムダを使用できます。

transform(options.begin(), options.end(), back_inserter(callbacks_), 
    [this](const OptionsMap::value_type &v) {
        return boost::bind(&ClassOutput::write_option_, this, v);
    }
);
于 2010-01-04T18:59:17.663 に答える