Get the latest tech news
Recursive Macros with C++20 __VA_OPT__
June, 2021 Wouldn’t it be nice if you could define pretty-printable enums in C++? Well, in C++20, you can define a macro that both creates an enum type and defines a function converting the enum values to strings. Here’s an example of such a macro in action: (MyType, ZERO, ONE, TWO, THREE); MAKE_ENUM void (MyType e) test{ std::cout << to_cstring(e) << " = " << e << std::endl; } int () main{ (ZERO); test(ONE); test(TWO); test(THREE); test} Output: ZERO = 0 ONE = 1 TWO = 2 THREE = 3 The key to making this work is a new pre-processor feature in C++20, __VA_OPT__(x), which expands to x when a variable-argument macro has more than zero arguments and to nothing otherwise.
Macro expansion occurs after the C/C++ preprocessor, cpp, has turned the program source code into a series of lexical tokens. C++ isn’t a great language for generating text, and if you use perl or python or bash, the code won’t necessarily be more transparent to other C++ programmers. Whatever you think of the trade-offs, this much is certain: the introduction of__VA_OPT__ makes FOR_EACH decidedly more palatable than the brittle and disgusting approaches with older versions of C++, to the point that it’s at least worth seriously considering.
Or read this on Hacker News