std::for_each,使用引用参数调用成员函数

发布于 07-14 20:35 字数 888 浏览 11 评论 0原文

我有一个指针容器,我想对其进行迭代,调用一个具有引用参数的成员函数。 我如何使用 STL 做到这一点?

我当前的解决方案是使用 boost::bind 和 boost::ref 作为参数。

// Given:
// void Renderable::render(Graphics& g)
//
// There is a reference, g, in scope with the call to std::for_each
//
std::for_each(
  sprites.begin(),
  sprites.end(),
  boost::bind(&Renderable::render, boost::ref(g), _1)
);

一个相关的问题(我从中得出当前的解决方案)是 boost::bind 与参数为引用的函数。 这特别询问如何使用 boost 来做到这一点。 我问的是,如果没有升压,这将如何完成。

编辑:有一种方法可以在不使用任何boost的情况下完成同样的事情。 通过使用 std::bind 和朋友,可以在 C++11 兼容编译器中编写和编译相同的代码,如下所示:

std::for_each(
  sprites.begin(),
  sprites.end(),
  std::bind(&Renderable::render, std::placeholders::_1, std::ref(g))
);

I have a container of pointers which I want to iterate over, calling a member function which has a parameter that is a reference. How do I do this with STL?

My current solution is to use boost::bind, and boost::ref for the parameter.

// Given:
// void Renderable::render(Graphics& g)
//
// There is a reference, g, in scope with the call to std::for_each
//
std::for_each(
  sprites.begin(),
  sprites.end(),
  boost::bind(&Renderable::render, boost::ref(g), _1)
);

A related question (from which I derived my current solution from) is boost::bind with functions that have parameters that are references. This specifically asks how to do this with boost. I am asking how it would be done without boost.

Edit: There is a way to do this same thing without using any boost. By using std::bind and friends the same code can be written and compiled in a C++11-compatible compiler like this:

std::for_each(
  sprites.begin(),
  sprites.end(),
  std::bind(&Renderable::render, std::placeholders::_1, std::ref(g))
);

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

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

发布评论

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

评论(1

世态炎凉2024-07-21 20:35:30

这是设计的问题。 您必须使用 boost::bind 或 tr1::bind。

This is a problem with the design of <functional>. You either have to use boost::bind or tr1::bind.

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