How to call a member function on a parameter with std::for_each and boost::bind?
I want to add a series of strings to a combo box using std::for_each. The objects are 开发者_如何学编程of type Category
and I need to call GetName
on them. How can I achieve this with boost::bind
?
const std::vector<Category> &categories = /**/;
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, _1);
The current code fails as it's trying to call CComboBox::AddString(category)
. Which is obviously wrong. How can I call CComboBox::AddString(category.GetName())
using the current syntax?
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, boost::bind(&Category::GetName, _1)));
You can use lambdas, either Boost.Lambda or C++ lambdas (if your compiler supports them):
// C++ lambda
const std::vector<Category> &categories = /**/;
std::for_each(categories.begin(), categories.end(),
[&comboBox](const Category &c) {comboBox.AddString(c.GetName());});
I know you asked about using std::for_each, but in those cases I like using BOOST_FOREACH instead, it makes the code more readable (in my opinion) and easier to debug:
const std::vector<Category> &categories = /**/;
BOOST_FOREACH(const Category& category, categories)
comboBox.AddString(category.GetName());
A possible way to achieve this would be using mem_fun
and bind1st
精彩评论