Capturing this in Lambdas

How can I use a lambda to create a function pointer that calls a member function of my class?

In C++, lambdas can capture the this pointer, allowing them to call member functions of the enclosing class. This can be useful when you need to create a function pointer that wraps a member function. Here's an example:

#include <iostream>

class Player {
 public:
  bool isAlive() const { return mAlive; }
  void setAlive(bool Alive) { mAlive = Alive; }

  template <typename Func>
  void useHealthPotion(Func&& onHealthRestored) {
    mAlive = true;
    onHealthRestored();
  }

 private:
  bool mAlive{true};
};

int main() {
  Player MyPlayer;
  MyPlayer.setAlive(false);

  MyPlayer.useHealthPotion([&MyPlayer]() {
    if (MyPlayer.isAlive()) {
      std::cout << "Health restored!\n";  
    }
  });
}
Health restored!

In this example, the Player class has a useHealthPotion member function that takes a function pointer (or any callable object) as an argument. We use a lambda to create this function pointer inline.

The lambda captures MyPlayer by reference using [&MyPlayer]. This allows the lambda to access MyPlayer and call its member functions, such as isAlive().

When useHealthPotion is called, it sets the player's mAlive state to true and then invokes the provided function pointer (onHealthRestored). The lambda, which captures MyPlayer, is able to call MyPlayer.isAlive() to check the player's state and print a message.

By capturing this (explicitly or implicitly), lambdas can create function pointers that have access to the enclosing class's member functions and state. This can be a convenient way to create callback functions or hook into class functionality without having to define separate free functions.

Function Pointers

Learn about function pointers: what they are, how to declare them, and their use in making our code more flexible

Questions & Answers

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

Storing Function Pointers
How can I store multiple function pointers of the same type in a collection like a vector or array?
Pointers to Member Functions
Is it possible to create a pointer to a member function of a class? If so, how is it different from a regular function pointer?
Function Pointers and Const
How does const-correctness apply to function pointers? Can I have a pointer to a const function?
Function Pointers and Inheritance
Can I assign a derived class member function to a base class function pointer? How does inheritance affect function pointers?
Using Function Pointers with STL Algorithms
Can I use function pointers with STL algorithms like std::find_if or std::sort? How can I pass a function pointer as a predicate or comparison function?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant