Home >Backend Development >C++ >How to Correctly Use Member Function Pointers with std::function?

How to Correctly Use Member Function Pointers with std::function?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 13:40:101046browse

How to Correctly Use Member Function Pointers with std::function?

How to Handle Member Function Pointers in std::function Objects

When working with member functions within std::function objects, certain complications can arise. Consider the following code:

#include <functional>

class Foo {
public:
    void doSomething() {}
    void bindFunction() {
        // ERROR
        std::function<void(void)> f = &Foo::doSomething;
    }
};

An error arises because non-static member functions implicitly pass the "this" pointer as an argument. However, the std::function signature here does not account for this argument.

Solution: Binding Member Functions to std::function Objects

To address this issue, the first argument ("this") must be explicitly bound:

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

For functions with parameters, placeholders can be utilized:

using namespace std::placeholders;
std::function<void(int, int)> f = std::bind(&Foo::doSomethingArgs, this, _1, _2);

In C 11, lambdas can also be employed:

std::function<void(int, int)> f = [=](int a, int b) {
    this->doSomethingArgs(a, b);
};

By incorporating these techniques, programmers can successfully work with member function pointers within std::function objects, effectively managing the implicit "this" argument.

The above is the detailed content of How to Correctly Use Member Function Pointers with std::function?. 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