mem_fun_ref function template — Creates a function object to call a member function via a reference
template<typename Rtn, typename T> const_mem_fun_ref_t<Rtn,T> mem_fun_ref(Rtn (T::*f)( ) const); template<typename Rtn, typename T, typename Arg> const_mem_fun1_ref_t<Rtn,T,Arg> mem_fun_ref(Rtn (T::*f)(Arg) const); template<typename Rtn, typename T> mem_fun_ref_t<Rtn,T> mem_fun_ref(Rtn (T::*f)( )); template<typename Rtn, typename T, typename Arg> mem_fun1_ref_t<Rtn,T,A> mem_fun_ref(Rtn (T::*f)(Arg));
The mem_fun_ref
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 an object of type T
(or a derived class). The object is
passed by reference to the functional. The Rtn
template parameter is the return type
of the member function; 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_ref
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
objects. As in Example 13-11, 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, or false
if the
employee is unlucky. Example
13-12 shows how to remove all the unlucky employees from the
container.
Example 13-12. Wrapping a member function called via a reference 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> emps;
// Fill emps with Employee objects.
...
// Erase the employees who will NOT receive bonuses. The call to remove_if
// rearranges emps; the call to erase removes the unlucky employees from the
// list.
emps.erase(
std::remove_if(emps.begin( ), emps.end( ),
std::not1(std::mem_fun_ref(&Employee::gets_bonus))),
emps.end( ));