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

Zac*_*man 8 c++ stl pass-by-reference

我有一个指针容器,我想迭代,调用一个成员函数,其参数是一个参考.如何使用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)
);
Run Code Online (Sandbox Code Playgroud)

一个相关的问题(我从中派生出我当前的解决方案)是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))
);
Run Code Online (Sandbox Code Playgroud)

dir*_*tly 5

这是设计的一个问题<functional>.你要么必须使用boost :: bind或tr1 :: bind.