views:

89

answers:

4

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?

+8  A: 
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, boost::bind(&Category::GetName, _1)));
baton
+4  A: 

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());});
Andreas Magnusson
Thanks for those suggestions, VS2008 doesn't support lambdas though (I guess I should have specified that in the tags).
Mark Ingram
VS2008 supports Boost.Lambda.
Andreas Magnusson
Anyway, I removed the Boost.Lambda example since it was incorrect and a correct one would look more like the accepted answer.
Andreas Magnusson
Ah, that explains why it didn't work :)
Mark Ingram
A: 

A possible way to achieve this would be using mem_fun and bind1st

hype
+2  A: 

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);
Edison Gustavo Muenz
+1 from me. BOOST_FOREACH is an incredibly cool feat. The inventor Eric Niebler wrote an article describing it: http://www.artima.com/cppsource/foreach.html. Minor nitpick, if you use braces it becomes more clear how incredibly cool BOOST_FOREACH is.
Andreas Magnusson