Home > Backend Development > C++ > How to Correctly Bind C Member Functions to std::function Objects?

How to Correctly Bind C Member Functions to std::function Objects?

Patricia Arquette
Release: 2024-12-19 07:53:09
Original
188 people have browsed it

How to Correctly Bind C   Member Functions to std::function Objects?

Binding Member Functions to Generic std::function Objects

In C , you may encounter situations where you need to store function pointers to member functions of a particular class in a container that accepts std::function objects. However, attempting to bind a non-static member function directly to a std::function can lead to errors.

Consider the following code:

#include <functional>

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

This code will result in a compiler error because non-static member functions implicitly accept a "this" pointer as their first argument. To resolve this issue, you need to bind the object in advance using the std::bind function.

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

This version correctly binds the "this" pointer to the member function, allowing you to store it in the std::function object without triggering the error.

For member functions that accept parameters, you can use std::placeholders to specify their positions:

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

Alternatively, if your compiler supports C 11 lambdas, you can use them to create the std::function object:

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

By utilizing these techniques, you can effectively bind member functions to generic std::function objects, enabling you to store and manipulate them conveniently.

The above is the detailed content of How to Correctly Bind C Member Functions to 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