Last active
February 12, 2021 08:28
-
-
Save pkierski/db71e026b74a322c0b13865de0f91c08 to your computer and use it in GitHub Desktop.
DeferredCall
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 characters
| #include <memory> | |
| #include <functional> | |
| #include <exception> | |
| class DeferredCall | |
| { | |
| public: | |
| DeferredCall(std::function<void()> callable) | |
| : callable{std::move(callable)} | |
| { | |
| } | |
| ~DeferredCall() | |
| { | |
| if(callable) | |
| { | |
| try | |
| { | |
| callable(); | |
| } | |
| catch(const std::exception&) | |
| { | |
| } | |
| } | |
| } | |
| void Cancel() | |
| { | |
| callable = decltype(callable){}; | |
| } | |
| private: | |
| std::function<void()> callable; | |
| }; | |
| // example | |
| #include <iostream> | |
| void foo() | |
| { | |
| std::cout << "foo" << std::endl; | |
| } | |
| void bar(int x) | |
| { | |
| std::cout << "bar(" << x << ")" << std::endl; | |
| } | |
| int main(int argc, char* argv[]) | |
| { | |
| DeferredCall deferredFoo(foo); | |
| DeferredCall deferredBar1([]{bar(1);}); | |
| DeferredCall deferredBar42([]{bar(42);}); | |
| deferredBar1.Cancel(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment