我有一个指针容器,我想迭代它,调用一个成员函数,该函数的参数是一个引用。我如何使用 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/