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

8

我有一个指针容器,我想遍历它,并调用一个带有引用参数的成员函数。如何使用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来做到这一点。 编辑:有一种方法可以在不使用任何boost的情况下完成相同的事情。通过使用std::bind和相关功能,可以像这样在C++11兼容的编译器中编写和编译相同的代码:
std::for_each(
  sprites.begin(),
  sprites.end(),
  std::bind(&Renderable::render, std::placeholders::_1, std::ref(g))
);

boost::bind(&Renderable::render, _1, boost::ref(g)) 应该改为 boost::bind(&Renderable::render, boost::ref(g), _1 ) - Carl
@carleeto 好的发现。在错误了4年之后修复了它! - Zack The Human
1个回答

5

这是关于<functional>设计的问题。你需要使用boost::bind或tr1::bind。


是的,可悲的是 :( 更多信息可以在这里找到:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2000/n1245.ps和http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#106。它似乎从未进入标准中。但它将出现在下一个标准中 :) - Johannes Schaub - litb
是的,引用到引用的问题正是我的问题。感谢您提供的信息! - Zack The Human

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接