In my opinion, it would be wiser to take std::function<void()> as an argument. The user of the interface will be able to capture the arguments on his own, for this purpose there are lambdas and std::bind in the language, allowing, among other things, capturing by reference.
#include <utility> #include <functional> #include <iostream> class SimpleButton{ std::function<void()> _action; public: void setAction(std::function<void()> fn){ _action = std::move(fn); } void click(){ _action(); } }; void printAB(int a, int b){ std::cout<< a << ", " << b << '\n'; } void test(){ SimpleButton button; int a = 1; int b = 10; // a захватывается по значению, b - по ссылке button.setAction(std::bind(&printAB, a, std::ref(b))); button.click(); // 1, 10 a = 20; b = 200; button.click(); // 1, 200 // аналогично через лямбды button.setAction([a, &b]{ std::cout<< a << ", " << b << '\n'; }); button.click(); // 20, 200 a = 300; b = 3000; button.click(); // 20, 3000 }
addActiondo with these unnecessary arguments ??? How should she "assign" them to theFAction? - AnT 6:23 pm