Object Call Function

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

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

I know a boost::lambda

 class Object { public: int run(){/* change object state */} }; vector<Object> v(10); for_each(v.begin(), v.end(), bind(&Object::run, _1)); 

but I wonder if this is the standard ( non-Cxx11 ) way to do this.

+4
source share
2 answers

There is (was) a 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/

+7
source

For anyone interested, here is a more detailed example of 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 (maximum for C ++ 03), you can

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

Note that you are linking the second argument. The first is the this pointer for the current object. Do you remember that any member function always takes this as the first parameter?

And the lambda path (C ++ 11) is 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 is for the situation where you have an argument. As for C ++ 11, it easily extends to more parameters

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

Source: https://habr.com/ru/post/1437112/


All Articles