c++ - std::for_each,调用带有引用参数的成员函数

标签 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)
);

一个相关的问题(我从中得出当前的解决方案)是 boost::bind with functions that have parameters that are references .这个专门问如何用boost来做到这一点。我想问的是没有 boost 怎么办。

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

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

最佳答案

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

关于c++ - std::for_each,调用带有引用参数的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/637441/

相关文章:

c++ - glm::ivec2 作为无序映射中的键

c++ - 如何开启STL向后兼容?

algorithm - 为什么是 `copy_n` 、 `fill_n` 和 `generate_n` ?

C++ 将指针传递给函数

c++ - 为什么我不能在从算术运算符返回时将此类作为引用传递?

c++如何将迭代器指针传递给需要引用对象的函数

c++ - 如何在不删除指针指向的数据的情况下删除指针?

c++ - linux 上的运算符 new 和 bad_alloc

c++ - 树莓派工具链上的 std::shared_future

C++ 返回 boolean 值 95