...

/

Implementing a Simple Button Class with std::function

Implementing a Simple Button Class with std::function

Discover how to implement a Button class using std::function and its optimization.

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:

Press + to interact
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 container because they all have the same type:

Press + to interact
auto create_buttons () {
auto beep = Button([counter = 0]() mutable {
std::cout << "Beep:" << counter << "! ";
++counter;
});
auto bop = Button([] { std::cout << "Bop. "; });
auto silent = Button([] {});
return std::vector<Button>{beep, bop, silent};
}

Iterating the list and calling on_click() on each button will execute the corresponding function:

Press + to interact
const auto& buttons = create_buttons();
for (const auto& b : buttons) {
b.on_click();
}
buttons.front().on_click(); // counter has been incremented
// Output "Beep: 0! Bop. Beep: 1!"
...