2

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?

Mark Ingram
  • 71,849
  • 51
  • 176
  • 230

4 Answers4

8
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, boost::bind(&Category::GetName, _1)));
baton
  • 297
  • 1
  • 3
4

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
  • 7,321
  • 3
  • 31
  • 36
3

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());
Gustavo Muenz
  • 9,278
  • 7
  • 40
  • 42
  • +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 Sep 22 '10 at 06:58
0

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

mukeshkumar
  • 2,698
  • 3
  • 19
  • 20