Skip to content

Instantly share code, notes, and snippets.

@pzelasko
Last active September 7, 2016 19:03
Show Gist options
  • Save pzelasko/5c409d3214c97c7abe5509aa0fd07546 to your computer and use it in GitHub Desktop.
Save pzelasko/5c409d3214c97c7abe5509aa0fd07546 to your computer and use it in GitHub Desktop.
Go-like defer in C++
#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