Skip to content

Instantly share code, notes, and snippets.

@Inori
Forked from pmttavara/defer.hpp
Created July 4, 2023 04:05
Show Gist options
  • Save Inori/a5cd22c2cce8c7fe33987cebb8d5d114 to your computer and use it in GitHub Desktop.
Save Inori/a5cd22c2cce8c7fe33987cebb8d5d114 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