tags:

views:

223

answers:

2

I'm wondering how to implement what is stated in the title. I've tried something like...

std::for_each( a.begin(), a.end(), std::mem_fun_ref( &myClass::someFunc ) )

but I get an error saying that the "term" (I"m assuming it means the 3rd argument) doesn't evaluate to a function with 1 argument, even though someFunc does take one argument - the type of the objects stored in a.

I'm wondering if what I'm trying to do is possible using the standard library (I know I can do it easily using boost).

P.S. Does using for_each and mem_fun_ref have any performance implications in comparison to just iterating through a manually and passing the object to someFunc?

+1  A: 

I think you need to use bind_1st to supply the hidden "this" argument. Or do you mean that the "this" argument is the only one, someFunc has no parameters of its own?

Ben Voigt
someFunc has one parameter. Like myClass::someFunc( someType ).
Person
+1  A: 

Even though someFunc is a member with one parameter, mem_fun_ref uses an implicit first argument of "myClass". You want to use the vector's items as the 2nd argument .

And there are probably no negative performance implications of using for_each and mem_fun_ref. The compiler will generate comparable code. But, the only way to be sure is to benchmark :)

  std::for_each(a.begin(), a.end(),
                std::bind1st(
                    std::mem_fun_ref( &MyClass::SomeFunc ),
                    my_class ));
Stephen
I assume I would use bind2nd then. Now I'm thinking how to go about specifying to use the current element in the iteration for it. I think I'll just use boost..
Person
Nope, still uses bind1st. mem_fun_ref becomes a function with two arguments. The first one is MyClass, the second one is your member function param. You want to bind the 1st argument to mem_fun_ref to your class instance.
Stephen
@Person: If you're gonna use Boost, I'd recommend using their foreach macro. `std::for_each` was simply a failed idea, and often leads for more spread-out, harder to read code.
GMan
`s/my_class/this/`. Hey, in C++03 at least, `for_each` saves the excessive tedium of declaring the iterator.
Potatoswatter