Yes, you can store a member function in a std::function
object, but you need to provide an object instance on which to invoke the member function. This is because a member function requires an object to be called on.
Here's an example of how you can store a member function in a std::function
and invoke it:
#include <functional>
#include <iostream>
class MyClass {
public:
void MyMethod(int x) {
std::cout << "MyMethod called with: "
<< x << "\n";
}
};
int main() {
MyClass obj;
std::function<void(MyClass*, int)> Callable{
&MyClass::MyMethod};
Callable(&obj, 42);
}
MyMethod called with: 42
In this example, we store a pointer to the MyMethod
member function of MyClass
in the Callable
std::function
object. The std::function
is declared with a signature that takes a MyClass*
as the first argument (the object to call the method on) and an int
as the second argument (the argument to pass to MyMethod
).
When invoking Callable
, we pass a pointer to obj
(an instance of MyClass
) as the first argument, and 42
as the second argument.
Alternatively, if you have a std::shared_ptr
to your object, you can use std::bind
to bind the member function to the object and store the result in a std::function
:
#include <functional>
#include <iostream>
#include <memory>
class MyClass {
public:
void MyMethod(int x) {
std::cout << "MyMethod called with: "
<< x << "\n";
}
};
int main() {
auto obj{std::make_shared<MyClass>()};
std::function<void(int)> Callable{
std::bind(
&MyClass::MyMethod,
obj,
std::placeholders::_1
)
};
Callable(42);
}
MyMethod called with: 42
Here, std::bind
creates a new callable that invokes MyMethod
on obj
when called. The std::placeholders::_1
is a placeholder for the argument that will be passed to Callable
.
Answers to questions are automatically generated and may not have been reviewed.
A comprehensive overview of function helpers in the standard library, including std::invocable
, std::predicate
and std::function
.