George2 a écrit :
Hello everyone,
In the following statements,
-
template <class R, class Tclass mem_fun_t : public unary_function
-
<T*, R>
-
{
-
R (T::*pmf)()
-
...
-
}
-
1. I think pmf is a type of function pointer, the return type of the
function is R and the function is a member function of type (class) T.
Is my understanding correct?
yes.
In brief it iss a pointer on a member fucntion of class T.
>
2. If yes, what is the parameter list of the function? Empty parameter
list?
Yes. No parameters.
>
3. I doubt whether it is useful to define a function pointer with
empty parameter list -- too restricted.
It is useful if you want to call a method of a class that takes no
parameters.
struct foo
{
static int gcounter=0;
foo(){id_=gcounter++;}
void bar(){std::cout<<"My id is "<<id_<<std::endl;}
int id_;
};
std::vector<foov(10);
std::for_each(v.begin(),v.end(),std::mem_fun_ref(& foo::bar));
Of course, you could put parameters in a class and make it a wrapper
class of a more elaborate functor.
Another example from SGI:
struct B {
virtual void print() = 0;
};
struct D1 : public B {
void print() { cout << "I'm a D1" << endl; }
};
struct D2 : public B {
void print() { cout << "I'm a D2" << endl; }
};
int main()
{
vector<B*V;
V.push_back(new D1);
V.push_back(new D2);
V.push_back(new D2);
V.push_back(new D1);
for_each(V.begin(), V.end(), mem_fun(&B::print));
}
Michael