why the member function mem_fun calls must be a const one?

369 views Asked by At

mem_fun and mem_fun_ref and many other member function adaptors can make member functions act like orindinary functions. But there is one restriction that the member function that they call must be a const one. I get to know how to use them, but confused and puzzled by the reasons behind it. Why is it designed in this way?

update: Sorry for the ambiguity. write an example below.

class A
{
    ...
    //void fun(){cout<<"Fun";} This is not const and the compiler would complain
    void fun() const {cout<<"Not fun";}
    ...
}
vector<A> avec;
...
for_each(avec.begin(),avec.end(),mem_fun_ref(&A::fun));
...
1

There are 1 answers

1
Vlad from Moscow On BEST ANSWER

There is no such a restriction. These template functions are overloaded for const and non-const member functions.

For example

template<class S, class T>
mem_fun_t<S,T> mem_fun(S (T::*f)());

template <class S, class T>
const_mem_fun_t<S,T> mem_fun(S (T::*f)() const);