Last active
November 19, 2024 16:38
-
-
Save nickel-dev/6f4419fe6ef613f0c45583598d21b813 to your computer and use it in GitHub Desktop.
jai defer in C++ (as a macro)
This file contains hidden or 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
// creates a variable called "__defer + line number" this variable is destructed at the end of the scope. | |
// on destruction it calls a lambda function that was generated by the macro. | |
// example: | |
// This program outputs "x: 1" | |
/* | |
{ | |
int x = 0; | |
defer(printf("x: %d\n", x)); | |
x++; | |
} | |
*/ | |
#define defer(...) auto __defer##__LINE__ = lambda_defer([&](void){##__VA_ARGS__##;}); | |
template <typename Callable> | |
struct Defer_Template { | |
Callable func; | |
Defer_Template(Callable f) : func(f) {} | |
~Defer_Template() { | |
func(); | |
} | |
}; | |
template <typename Callable> | |
inline Defer_Template<Callable> lambda_defer(Callable f) { | |
return Defer_Template<Callable>(f); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment