【问题标题】:How to call a member function on a parameter with std::for_each and boost::bind?如何使用 std::for_each 和 boost::bind 在参数上调用成员函数?
【发布时间】:2010-09-21 12:06:39
【问题描述】:

我想使用 std::for_each 将一系列字符串添加到组合框。这些对象的类型为Category,我需要对它们调用GetName。如何使用boost::bind 实现这一目标?

const std::vector<Category> &categories = /**/;
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, _1);

当前代码在尝试调用CComboBox::AddString(category) 时失败。这显然是错误的。如何使用当前语法调用CComboBox::AddString(category.GetName())

【问题讨论】:

  • 是否有必要使用std::foreach 而不是迭代?
  • 不是绝对必要,只是想学习boost。

标签: c++ visual-studio-2008 boost stl boost-bind


【解决方案1】:
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, boost::bind(&Category::GetName, _1)));

【讨论】:

    【解决方案2】:

    您可以使用 lambda,Boost.Lambda 或 C++ lambda(如果您的编译器支持它们):

    // C++ lambda
    const std::vector<Category> &categories = /**/;
    std::for_each(categories.begin(), categories.end(),
                  [&comboBox](const Category &c) {comboBox.AddString(c.GetName());});
    

    【讨论】:

    • 感谢您的建议,但 VS2008 不支持 lambdas(我想我应该在标签中指定)。
    • VS2008 支持 Boost.Lambda。
    • 无论如何,我删除了 Boost.Lambda 示例,因为它不正确,而正确的示例看起来更像是接受的答案。
    【解决方案3】:

    我知道你问过关于使用 std::for_each 的问题,但在这些情况下,我更喜欢使用 BOOST_FOREACH,它使代码更具可读性(在我看来)并且更易于调试:

    const std::vector<Category> &categories = /**/;
    BOOST_FOREACH(const Category& category, categories)
        comboBox.AddString(category.GetName());
    

    【讨论】:

    • +1 来自我。 BOOST_FOREACH 是一项非常酷的壮举。发明者 Eric Niebler 写了一篇描述它的文章:artima.com/cppsource/foreach.html。轻微的挑剔,如果您使用大括号,就会更加清楚 BOOST_FOREACH 的酷炫程度。
    【解决方案4】:

    实现此目的的一种可能方法是使用mem_funbind1st

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 2013-11-12
      • 2011-06-23
      • 2015-03-19
      • 2016-10-04
      相关资源
      最近更新 更多