Skip to content

Instantly share code, notes, and snippets.

@nickel-dev
Last active November 19, 2024 16:38
Show Gist options
  • Save nickel-dev/6f4419fe6ef613f0c45583598d21b813 to your computer and use it in GitHub Desktop.
Save nickel-dev/6f4419fe6ef613f0c45583598d21b813 to your computer and use it in GitHub Desktop.
jai defer in C++ (as a macro)
// 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