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::functionf = 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::functionf = 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::functionf = [=](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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3