Question

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?

My current solution is to use boost::bind, and boost::ref for the parameter.

// 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. This specifically asks how to do this with 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. By using std::bind and friends the same code can be written and compiled in a C++11-compatible compiler like this:

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

Solution

This is a problem with the design of <functional>. You either have to use boost::bind or tr1::bind.

OTHER TIPS

Check out How to use std::foreach with parameters/modification. The question shows how to do it using a for loop. The accepted answer gives an example of how to achieve this with the for_each algorithm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top