Storing Member Functions in std::function

Can I store a member function in a std::function object? If so, how do I invoke it?

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.

Standard Library Function Helpers

A comprehensive overview of function helpers in the standard library, including std::invocable, std::predicate and std::function.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Calling an Empty std::function
What happens if I try to call a std::function object that is empty?
Performance Considerations with std::function
Are there any performance considerations I should be aware of when using std::function?
Using the Predicate Concept with Member Types
Can I use the std::predicate concept with member functions that take member types as arguments?
Invoking Multiple std::function Objects
How can I store and invoke multiple std::function objects?
Using Lambdas with std::function
Can I use lambda expressions with std::function? Are there any limitations?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant