"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Store Member Function Pointers in Generic `std::function` Objects?

How to Store Member Function Pointers in Generic `std::function` Objects?

Published on 2024-12-21
Browse:263

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 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 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 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.

Latest tutorial More>

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