Skip to content

Instantly share code, notes, and snippets.

@pmttavara
Created March 25, 2018 07:27
Show Gist options
  • Save pmttavara/089f5b0d670330fd6379365ac4c46d2e to your computer and use it in GitHub Desktop.
Save pmttavara/089f5b0d670330fd6379365ac4c46d2e to your computer and use it in GitHub Desktop.
The definitive defer implementation for C++. Syntax: defer { statements; };
#ifndef defer
struct defer_dummy {};
template <class F> struct deferrer { F f; ~deferrer() { f(); } };
template <class F> deferrer<F> operator*(defer_dummy, F f) { return {f}; }
#define DEFER_(LINE) zz_defer##LINE
#define DEFER(LINE) DEFER_(LINE)
#define defer auto DEFER(__LINE__) = defer_dummy{} *[&]()
#endif // defer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment