如何使用 std::for_each 和 boost::bind 在参数上调用成员函数?

发布于 2024-09-24 11:09:32 字数 470 浏览 0 评论 0原文

我想使用 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())

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风铃鹿 2024-10-01 11:09:32
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, boost::bind(&Category::GetName, _1)));
std::for_each(categories.begin(), categories.end(), boost::bind(&CComboBox::AddString, &comboBox, boost::bind(&Category::GetName, _1)));
水中月 2024-10-01 11:09:32

您可以使用 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());});

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());});
-小熊_ 2024-10-01 11:09:32

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

const std::vector<Category> &categories = /**/;
BOOST_FOREACH(const Category& category, categories)
    comboBox.AddString(category.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());
晚雾 2024-10-01 11:09:32

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文