Last active
April 5, 2021 14:27
Revisions
-
sasq64 revised this gist
Sep 21, 2016 . 1 changed file with 39 additions and 39 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -5,51 +5,51 @@ template<typename... X> struct Callback; template <typename R, typename ...ARGS> struct Callback<R(ARGS...)> { struct BaseFx { virtual R call(ARGS...) = 0; }; template <typename FX> struct Fx : public BaseFx { Fx(FX f) : f(f) {} virtual R call(ARGS... args) { return f(args...); }; FX f; }; using Holder = std::shared_ptr<std::function<void(std::nullptr_t)>>; template <typename FX> Holder add(FX f) { callbacks.push_back(std::make_shared<Fx<FX>>(f)); auto cb = callbacks.back(); return Holder(nullptr, [=](std::nullptr_t) { callbacks.erase(remove(callbacks.begin(), callbacks.end(), cb)); }); }; void call(ARGS... args) { for(auto &cb : callbacks) cb->call(args...); } std::vector<std::shared_ptr<BaseFx>> callbacks; }; int main() { // Outputs 5.0 Callback<void(float, float)> test; { auto holder = test.add([](float x, float y) { printf("%.1f\n", x+y); }); test.call(3.0f, 2.0f); } test.call(1.0f, 5.0f); return 0; } -
sasq64 created this gist
Sep 21, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ #include <functional> #include <vector> #include <memory> template<typename... X> struct Callback; template <typename R, typename ...ARGS> struct Callback<R(ARGS...)> { struct BaseFx { virtual R call(ARGS...) = 0; }; template <typename FX> struct Fx : public BaseFx { Fx(FX f) : f(f) {} virtual R call(ARGS... args) { return f(args...); }; FX f; }; using Holder = std::shared_ptr<std::function<void(std::nullptr_t)>>; template <typename FX> Holder add(FX f) { callbacks.push_back(std::make_shared<Fx<FX>>(f)); auto cb = callbacks.back(); return Holder(nullptr, [=](std::nullptr_t) { callbacks.erase(remove(callbacks.begin(), callbacks.end(), cb)); }); }; void call(ARGS... args) { for(auto &cb : callbacks) cb->call(args...); } std::vector<std::shared_ptr<BaseFx>> callbacks; }; int main() { // Outputs 5.0 Callback<void(float, float)> test; { auto holder = test.add([](float x, float y) { printf("%.1f\n", x+y); }); test.call(3.0f, 2.0f); } test.call(1.0f, 5.0f); return 0; }