Function Pointers to Member Functions with Standard Library Functions
In an attempt to store function pointers to member functions of a class within a map containing standard library function objects, a common error arises. As demonstrated in the code below, assigning a member function directly to a function object results in an error:
#include <functional> class Foo { public: void doSomething() {} void bindFunction() { // ERROR std::function<void(void)> f = &Foo::doSomething; } };
The error encountered is due to a member function's implicit requirement for an object. A member function is always called with an object, effectively passing the "this" pointer as its first argument.
To resolve this issue, the function signature must specify that the function doesn't take any arguments (
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
If the function requires parameters, placeholders can be used:
using namespace std::placeholders; std::function<void(int, int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);
C 11 lambdas can also be utilized:
std::function<void(int, int)> f = [=](int a, int b) { this->doSomethingArgs(a, b); };
The above is the detailed content of How to Store Member Function Pointers in Standard Library Function Objects?. For more information, please follow other related articles on the PHP Chinese website!