Last active
November 20, 2022 17:45
-
-
Save gingerBill/dbf7b10c707b03279e34 to your computer and use it in GitHub Desktop.
Golang Defer in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//////////////////////////////////////////////////////////////// | |
// | |
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incredibly verbose implementation; long lines. Hungarian warts. Unnecessary macro layers. Counter not always defined.