views:

1011

answers:

2

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, _1, boost::ref(g))
);

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.

+1  A: 

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.

Matt Davis
+3  A: 

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

dirkgently
yep, sadly :( more information on this: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2000/n1245.ps and http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#106 which apparently never got into the standard. But it's in the next one :)
Johannes Schaub - litb
Yes, the references-to-references problems was exactly my issue. Thanks for the info!
Zack Mulgrew