Home > Backend Development > C++ > How to Store Member Function Pointers in Generic `std::function` Objects?

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

Linda Hamilton
Release: 2024-12-23 20:39:10
Original
250 people have browsed it

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);
Copy after login

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);
Copy after login

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);
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template