Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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))
);
like image 282
Zack The Human Avatar asked Mar 12 '09 05:03

Zack The Human


1 Answers

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

like image 59
dirkgently Avatar answered Oct 06 '22 02:10

dirkgently