Last active
September 7, 2016 19:03
-
-
Save pzelasko/5c409d3214c97c7abe5509aa0fd07546 to your computer and use it in GitHub Desktop.
Go-like defer in C++
This file contains 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 <iostream> | |
#include <string> | |
namespace impl { | |
template <typename Fun> struct DeferredWrapper | |
{ | |
Fun f_; | |
DeferredWrapper(Fun &&f) : f_{std::forward<Fun>(f)} {} | |
~DeferredWrapper() { | |
f_(); | |
} | |
}; | |
} | |
template <typename Fun> | |
auto on_scope_exit(Fun &&f) { | |
return impl::DeferredWrapper<Fun>{std::forward<Fun>(f)}; | |
} | |
// example of usage | |
void foo() { | |
std::cout << "on entry" << std::endl; | |
std::string s = "on exit"; | |
auto _ = on_scope_exit([&](){ std::cout << s << std::endl;}); | |
std::cout << "middle" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment