4 ms·
> Here, there's a conflict between the lexical scope of the function (main) and the macro (SWAP). It might interest to some to know that GCC has a macro called
by blippage 4y ago
> Here, there's a conflict between the lexical scope of the function (main) and the macro (SWAP).
It might interest to some to know that GCC has a macro called __COUNTER__ (apparently also implemented by clang and MS), which auto-increments its value. You can then create something like a gensym to avoid conflict.
Here's an implementation of the "defer" keyword in C++:
template <typename F>
struct privDefer {
F f;
privDefer(F f) : f(f) {}
~privDefer() { f(); }
};
template <typename F>
privDefer<F> defer_func(F f) {
return privDefer<F>(f);
}
#define DEFER_1(x, y) x##y
#define DEFER_2(x, y) DEFER_1(x, y)
#define DEFER_3(x) DEFER_2(x, __COUNTER__)
#define defer(code) auto DEFER_3(_defer_) = defer_func([&](){code;})
It was written by gingerBill, author of the Odin programming language.
- zdimension 4y agoTIL, I'd never have thought something line gensyn could be possible using C macros (though this is an extension). This is both amazing and horrible
- leni536 4y agoI would advice against using __COUNTER__ or macros based on that in header files. It's an ODR-violation footgun.