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