简体   繁体   English

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

[英]std::for_each, calling member function with reference parameter

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? 如何使用STL执行此操作?

My current solution is to use boost::bind, and boost::ref for the parameter. 我目前的解决方案是使用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)
);

A related question (from which I derived my current solution from) is boost::bind with functions that have parameters that are references . 一个相关的问题(我从中派生出我当前的解决方案)是boost :: bind,其函数的参数是引用 This specifically asks how to do this with boost. 这特别询问如何使用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 . 编辑 :有一种方法可以做同样的事情而不使用任何boost By using std::bind and friends the same code can be written and compiled in a C++11-compatible compiler like this: 通过使用std::bind和friends,可以在兼容C ++ 11的编译器中编写和编译相同的代码,如下所示:

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

This is a problem with the design of <functional> . 这是<functional>设计的一个问题。 You either have to use boost::bind or tr1::bind. 你要么必须使用boost :: bind或tr1 :: bind。

Check out How to use std::foreach with parameters/modification . 查看如何使用参数/修改std :: foreach The question shows how to do it using a for loop. 问题显示了如何使用for循环来完成它。 The accepted answer gives an example of how to achieve this with the for_each algorithm. 接受的答案给出了如何使用for_each算法实现此目的的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM