Standard Library Function Helpers

Storing Member Functions in std::function

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

Abstract art representing computer programming

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 computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved