mem_fun_ref

A

Anders

Hello.
If I was to call a method of class T, M for each element in a collection,
I'd do it like this:

vector<int> vec;
....
for_each(vec.begin(), vec.end(), mem_fun_ref(&T::M));

Okay, I can see that mem_fun_REF makes it obvious that I must use a
reference, but why? Is it not possible to pass a function by-reference? As I
see it, T::M is being passed as a pointer here.

void func(int& val); func(12); << reference
void func(int* val); int val = 12; func(&val); << pointer

//Anders
 
K

Kurt Krueckeberg

Hello.
If I was to call a method of class T, M for each element in a collection,
I'd do it like this:

vector<int> vec;
...
for_each(vec.begin(), vec.end(), mem_fun_ref(&T::M));

Okay, I can see that mem_fun_REF makes it obvious that I must use a
reference, but why? Is it not possible to pass a function by-reference?

No, you can only pass the address.
As I see it, T::M is being passed as a pointer here.

The REF, in mem_fun_ref, refers to the argument type( of T::M ), which
will be passed to the function call operator.
 
T

tom_usenet

Hello.
If I was to call a method of class T, M for each element in a collection,
I'd do it like this:

vector<int> vec;
...
for_each(vec.begin(), vec.end(), mem_fun_ref(&T::M));

That can't be legal - you can't call a T member function on an int
reference.
Okay, I can see that mem_fun_REF makes it obvious that I must use a
reference, but why? Is it not possible to pass a function by-reference? As I
see it, T::M is being passed as a pointer here.

void func(int& val); func(12); << reference
void func(int* val); int val = 12; func(&val); << pointer

The ref refers to the the fact that the object passed as the first
argument of the functor must be a reference. e.g.

T t;

mem_fun_ref(&T::M)(t); //pass T reference

mem_fun(&T::M)(&t); //pass T pointer

so in practice you use mem_fun_ref for containers like:
vector<T>
and mem_fun for containers like:
vector<T*>

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top