Sam
Sam

Reputation: 20056

Call member function on object vector

Given a vector<Object>, where Object has a function run(), is there a way to call run() in a for_each, using only std functions/templates?

Note that run() is not a static function, it should actually transform the object being referenced (of course it's not the case in my small example)

I know the boost::lambda way

class Object
{
public:
    int run(){/* change object state */}
};

vector<Object> v(10);
for_each(v.begin(), v.end(), bind(&Object::run, _1));

but I am curious if it's a standard (non-Cxx11) way to do it.

Upvotes: 4

Views: 1681

Answers (2)

Sam
Sam

Reputation: 20056

For anyone interested, here is a more detailed example on how to use for_each

class Object
{
public:
    int run(){/* change object state */}
    int run2(char c){/* change object state */}
};

vector<Object> v(10);
char c = 'a';

If you want to send a parameter to your function (at max one, for C++03), you can

for_each(v.begin(), v.end(), std::bind2nd( std::mem_fun_ref(&Object::run2), c));

Note that you bind the second argument. The first one is a this pointer to the current object. Did you remember that any member function always takes this as first parameter?

And the lambda way (C++11) so much nicer!

for_each( v.begin(), v.end(), [&] (const Object& val)
{
    val.run();  
    // this is effectively the most flexible way to specify the function params
    val.run2(c); 
} );

Finally, the boost::lambda way, for the situation when you have an argument. As for the C++11, it is easy extendable to more parameters

for_each(v.begin(), v.end(), bind(&Holder::run, _1, c) );

Upvotes: 1

PiotrNycz
PiotrNycz

Reputation: 24412

There is (was) C++03 way:

for_each(v.begin(), v.end(), mem_fun_ref(&Object::run));

See http://www.cplusplus.com/reference/std/functional/mem_fun_ref/

Upvotes: 7

Related Questions