std::mem_fn
Defined in header <functional>
|
||
template< class R, class T > /*unspecified*/ mem_fn(R T::* pm);
|
(1) | (since C++11) |
template< class R, class T, class... Args > /*unspecified*/ mem_fn(R (T::* pm)(Args...));
template< class R, class T, class... Args > /*unspecified*/ mem_fn(R (T::* pm)(Args...) const); |
(2) | (c++11, but defect) |
Function template std::mem_fn generates wrapper objects for pointers to member functions, which can store, copy, and invoke a pointer to member function. Both references and pointers (including smart pointers) to an object can be used when invoking a std::mem_fn.
The overloads (2) are reported as defect. The resolution, which has recently been voted "Tentatively Ready" proposes to remove all the overloads (2). This will break some code, see Example 2.
Contents |
[edit] Parameters
pm | - | pointer to member function that will be wrapped |
[edit] Return value
std::mem_fn returns an object of unspecified simple call wrapper type, which has the following members:
[edit] Member types
type | definition |
result_type | pm's return Type |
argument_type | T*, possibly cv-qualified, if pm takes no arguments |
first_argument_type | T* if pm takes one argument |
second_argument_type | T1 if pm takes one argument of type T1 |
[edit] Member functions
invokes the target of an std::mem_fn (public member function) |
[edit] Exceptions
None.
[edit] Example 1
#include <iostream> #include <functional> #include <iterator> #include <memory> #include <string> #include <vector> #include <algorithm> int main() { std::vector<std::string> words = {"This", "is", "a", "test"}; std::vector<std::unique_ptr<std::string>> words2; words2.emplace_back(new std::string("another")); words2.emplace_back(new std::string("test")); std::vector<std::size_t> lengths; std::transform(words.begin(), words.end(), std::back_inserter(lengths), std::mem_fn(&std::string::size)); // uses references to strings std::transform(words2.begin(), words2.end(), std::back_inserter(lengths), std::mem_fn(&std::string::size)); // uses unique_ptr to strings std::cout << "The string lengths are "; for(auto n : lengths) std::cout << n << ' '; std::cout << '\n'; }
Output:
The string lengths are 4 2 1 4 7 4
[edit] Example 2
#include <functional> struct X { int x; int& easy() {return x;} int& get() {return x;} const int& get() const {return x;} }; int main(void) { auto a = std::mem_fn (&X::easy); // no problem at all // auto b = std::mem_fn<int& >(&X::get ); // no longer works with new specification auto c = std::mem_fn<int&()>(&X::get ); // works with both old and new specification auto d = [] (X& x) {return x.get();}; // this is the true c++11 return 0; }
[edit] See also
(C++11)
|
wraps callable object of any type with specified function call signature (class template) |
(C++11)
|
binds one or more arguments to a function object (function template) |