mem_fun function template — Creates a function object to call a member function via a pointer
template<typename Rtn, typename T> const_mem_fun_t<Rtn,T> mem_fun(Rtn (T::*f)( ) const); template<typename Rtn, typename T, typename Arg> const_mem_fun1_t<Rtn,T,Arg> mem_fun(Rtn (T::*f)(Arg) const); template<typename Rtn, typename T> mem_fun_t<Rtn,T> mem_fun(Rtn (T::*f)( )); template<typename Rtn, typename T, typename Arg> mem_fun1_t<Rtn,T,Arg> mem_fun(Rtn (T::*f)(Arg));
The mem_fun
function
template takes a pointer to a member function as an argument and
returns a function object that can call the member function. The
function object must be applied to a pointer to T
(or a derived class). The Rtn
template parameter is the return type
of the member function, and the T
template parameter is the object that has the member function. The
optional Arg
template parameter
is the type of the argument to the member function.
The mem_fun
function is
usually the simplest way to create a function object that wraps a
member function. In normal use, the compiler deduces the template
parameters.
Suppose you have an Employee
class and a container of Employee
pointers. One of the member
functions of Employee
is gets_bonus
, which returns a bool
: true
if the employee is lucky and gets a
bonus this year, and false
if the
employee is unlucky. Example
13-11 shows how to remove all the unlucky employees from the
container.
Example 13-11. Wrapping a member function called via a pointer as a function object
class Employee {
public:
int sales( ) const { return sales_; }
std::string name( ) const { return name_; }
bool gets_bonus( ) const { return sales( ) > bonus; }
...
};
std::list<Employee*> empptrs;
// Fill empptrs with pointers to Employee objects.
...
// Remove the employees who will NOT receive bonuses.
std::list<Employee*>::iterator last =
std::remove_if(empptrs.begin( ), empptrs.end( ),
std::not1(std::mem_fun(&Employee::gets_bonus)));