Home >Backend Development >C++ >How to Store Member Function Pointers in Generic `std::function` Objects?
Storing Member Function Pointers in Generic std::function Objects
When attempting to store member function pointers of a particular class in a map using std::function objects, developers may encounter an error: "term does not evaluate to a function taking 0 arguments." This error arises when assigning the member function pointer directly to the std::function object.
The crux of the issue lies in the fact that non-static member functions require an implicit "this" pointer as the first argument. To rectify this, the first argument must be explicitly bound.
Solution:
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
This approach effectively binds the "this" pointer as the first argument, allowing the std::function object to correctly capture the member function.
Handling Functions with Parameters:
For member functions with parameters, placeholders must be specified to indicate the position of the bound arguments.
using namespace std::placeholders; std::function<void(int, int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);
C 11 Lambda Syntax:
If the compiler supports C 11 lambdas, a more concise approach can be utilized:
std::function<void(int, int)> f = [=](int a, int b) { this->doSomethingArgs(a, b); };
By following these techniques, developers can effectively store and invoke member function pointers using generic std::function objects.
The above is the detailed content of How to Store Member Function Pointers in Generic `std::function` Objects?. For more information, please follow other related articles on the PHP Chinese website!