Skip to content

Instantly share code, notes, and snippets.

@gingerBill
Last active November 20, 2022 17:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gingerBill/dbf7b10c707b03279e34 to your computer and use it in GitHub Desktop.
Save gingerBill/dbf7b10c707b03279e34 to your computer and use it in GitHub Desktop.
Golang Defer in C++
////////////////////////////////////////////////////////////////
//
// Defer statement
// - Akin to D's SCOPE_EXIT or similar to Go's defer but scope-based
//
////////////////////////////////////////////////////////////////
#if defined(__cplusplus)
extern "C++" {
// NOTE(bill): Stupid fucking templates
template <typename T> struct gbRemove_Reference { typedef T Type; };
template <typename T> struct gbRemove_Reference<T &> { typedef T Type; };
template <typename T> struct gbRemove_Reference<T &&> { typedef T Type; };
// NOTE(bill): "Move" semantics - invented because the C++ committee are idiots (as a collective not as indiviuals (well a least some aren't))
template <typename T> gb_inline T &&gb_forward_ownership(typename gbRemove_Reference<T>::Type &t) { return static_cast<T &&>(t); }
template <typename T> gb_inline T &&gb_forward_ownership(typename gbRemove_Reference<T>::Type &&t) { return static_cast<T &&>(t); }
template <typename F>
struct gbImpl_Defer {
F f;
gbImpl_Defer(F &&f) : f(gb_forward_ownership<F>(f)) {}
~gbImpl_Defer() { f(); }
};
template <typename F> gbImpl_Defer<F> gb_defer_func(F &&f) { return gbImpl_Defer<F>(gb_forward_ownership<F>(f)); }
#ifndef defer
#define GB_DEFER_1(x, y) x##y
#define GB_DEFER_2(x, y) GB_DEFER_1(x, y)
#define GB_DEFER_3(x) GB_DEFER_2(x, __COUNTER__)
#define defer(code) auto GB_DEFER_3(_defer_) = gb_defer_func([&](){code;})
#endif
}
#endif
@Nameguy
Copy link

Nameguy commented May 4, 2016

Incredibly verbose implementation; long lines. Hungarian warts. Unnecessary macro layers. Counter not always defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment