C++
Utilities library
Function objects
Defined in header |
||
template< class M, class T > |
(since C++11) (until C++20) |
|
template< class M, class T > |
(since C++20) | |
Function template std::mem_fn
generates wrapper objects for pointers to members, which can store, copy, and invoke a pointer to member. Both references and pointers (including smart pointers) to an object can be used when invoking a std::mem_fn
.
pm | - | pointer to member that will be wrapped |
std::mem_fn
returns a call wrapper of unspecified type that has the following members:
Member types
|
(until C++20) |
template /* see below */ operator()(Args&&... args) /* cvref-qualifiers */ noexcept(/* see below */); |
(until C++20) | |
template constexpr /* see below */ operator()(Args&&... args) /* cvref-qualifiers */ noexcept(/* see below */); |
(since C++20) | |
Let fn
be the call wrapper returned by a call to std::mem_fn
with a pointer to member pm
. Then the expression fn(t, a2, ..., aN) is equivalent to INVOKE(pm, t, a2, ..., aN), where INVOKE is the operation defined in Callable.
Thus, the return type of operator()
is std::result_of
Each argument in args
is perfectly forwarded, as if by std::forward
Use mem_fn
to store and execute a member function and a member object:
Run this code
#include#include struct Foo { void display_greeting() { std::cout << "Hello, world.\n"; } void display_number(int i) { std::cout << "number: " << i << '\n'; } int data = 7; }; int main() { Foo f; auto greet = std::mem_fn(&Foo::display_greeting); greet(f); auto print_num = std::mem_fn(&Foo::display_number); print_num(f, 42); auto access_data = std::mem_fn(&Foo::data); std::cout << "data: " << access_data(f) << '\n'; }
Output:
Hello, world. number: 42 data: 7
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 2048 | C++11 | unnecessary overloads provided | removed |
LWG 2489 | C++11 | noexcept not required | required |
function (C++11) |
wraps callable object of any type with specified function call signature (class template) |
bind (C++11) |
binds one or more arguments to a function object (function template) |