2010-01-04 48 views
1

我有下面的代碼使用for循環,我想使用變換,或者至少是for_each,但我看不到如何。容器的boost ::函數對象的STL算法

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

回答

2

要做到這一切在一個單一的變換電話,你,我想你需要調用本身綁定,因爲你需要它調用一個函數對象提高:綁定。這是我從未嘗試過的。你會解決這樣的問題嗎(未經測試)?

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

這一個變化的作品。 operator()的參數應該是OptionsMap :: value_type。謝謝。 – 2010-01-04 19:33:28

+0

修復它(15個字符)。 – 2010-01-04 20:18:58

3

我設法找出第2部分:

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