I am developing a program where I find myself doing this like this a lot:
void Model::SetCollideMode( const std::string &m )
{
Body *body;
std::map<std::string, Body* >::iterator iter;
for (iter=this->bodies.begin(); iter!=this->bodies.end(); iter++)
{
body = iter->second;
body->SetCollideMode( m );
}
}
I have several methods like that in several object that basically apply a property to all its children. Coming from Ruby world I am dying to do something like:
for_all_bodies{ body->SetCollideMode(m) }
There is anyway to make this code more closures like or in other way improve it?
I am conscious of how C++ works, that it is stack based and there is no context information to create a perfect closure like functionality (this need a VM?) but at least improve over the current repeat this code 100 times kind of programming.
There are several approaches, none of them perfect.
First, the “conventional” approach would be to define a functor to do what you need:
This doesn’t save you a lot of code, but it does allow you to separate the iteration from the operation that you want to apply. And if you need to set collidemode multiple times, you can reuse the functor, of course.
A shorter version is possible with the Boost.Lambda library, which would allow you to define the functor inline. I can’t remember the exact syntax, as I don’t use Boost.Lambda often, but it’d be something like this:
In C++0x, you get language support for lambdas, allowing syntax similar to this without having to pull in third-party libraries.
Finally, Boost.ForEach might be an option, allowing syntax such as this: