Home >Backend Development >C++ >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; } };
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);
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);
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); }
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!