Home >Backend Development >C++ >How to Store Member Function Pointers in Standard Library Function Objects?

How to Store Member Function Pointers in Standard Library Function Objects?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 21:20:11931browse

How to Store Member Function Pointers in Standard Library Function Objects?

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 (). Additionally, the first (and only) argument must be bound. This can be achieved using std::bind():

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!

Statement:
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