Search⌘ K
AI Features

Implementing a Simple Button Class with std::function

Explore how to implement a simple Button class in C++ using std::function to store actions linked to button clicks. Understand the flexibility of std::function with lambdas, const-correctness nuances, and examine performance trade-offs including inlining limitations, dynamic memory use, and runtime overhead through benchmarking examples.

Using std::function to store actions in a Button class

Assume that we set out to implement a Button class. We can then use the std::function to store the action corresponding to clicking the button so that when we call the on_click() member function, the corresponding code is executed.

We can declare the Button class like this:

C++
class Button {
public:
Button(std::function<void(void)> click) : handler_{click} {}
auto on_click() const { handler_(); }
private:
std::function<void(void)> handler_{};
};

We can then use it to create a multitude of buttons with different actions. The buttons can conveniently be stored in a ...