Skip to content

Instantly share code, notes, and snippets.

@brhsiao brhsiao/defer.hpp
Created Feb 24, 2019

What would you like to do?
C++ defer macro
#include <utility>
template <typename F>
struct Defer {
Defer(F f) : f(f) {}
~Defer() { f(); }
F f;
template <typename F>
Defer<F> make_defer(F f) {
return Defer<F>(f);
#define __defer(line) defer_ ## line
#define _defer(line) __defer(line)
struct defer_dummy {};
template<typename F>
Defer<F> operator+(defer_dummy, F&& f) {
return make_defer<F>(std::forward<F>(f));
#define defer auto _defer(__LINE__) = defer_dummy() + [&]()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.