Last active
January 3, 2019 19:58
-
-
Save krabicezpapundeklu/ac6c5fae9d1429917b7ca6fc42bc8047 to your computer and use it in GitHub Desktop.
DEFER macro for 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
#pragma once | |
template | |
< | |
typename T | |
> | |
class defer | |
{ | |
public: | |
defer(T action) | |
: action_{action} | |
{ | |
} | |
~defer() | |
{ | |
action_(); | |
} | |
private: | |
T action_; | |
}; | |
template | |
< | |
typename T | |
> | |
defer<T> make_defer(T action) | |
{ | |
return defer<T>(action); | |
} | |
#define DEFER(...) \ | |
DEFER_IMPL_1(__LINE__, __VA_ARGS__) | |
#define DEFER_IMPL_1(LINE, ...) \ | |
DEFER_IMPL_2(LINE, __VA_ARGS__) | |
#define DEFER_IMPL_2(LINE, ...) \ | |
const auto defer_##LINE = make_defer([&](){__VA_ARGS__;}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: