Name

mem_fun function template — Creates a function object to call a member function via a pointer

Synopsis

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

Example 13-11. Wrapping a member function called via a pointer as a function ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.