Aussie AI
Variadic Macro Assertions
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Variadic Macro Assertions
C++ allows #define preprocessor macros to have variable arguments using the “...
” and “__VA_ARG__
” special tokens.
Our yassert
macro changes to:
#define yassert(cond, ...) \ ( (cond) || \ aussie_yassert_fail(#cond, __FILE__, __LINE__, __VA__ARG__) )
And we change our “aussie_yassert_fail
” to have an extra optional “message” parameter.
bool aussie_yassert_fail(char* str, char* fname, int ln, char *mesg=0);
This all works fine if the yassert
macro has 2 arguments (condition and extra message)
but we get a bizarre compilation error if we omit the extra message (i.e. just a basic assertion with a condition).
The problem is that __VA_ARG__
expands to nothing (because there's no optional extra message argument),
and the replacement text then has an extra “,
” just hanging there at the end of the argument list, causing a syntax error.
Fortunately, the deities who define C++ standards noticed this problem and added a solution in C++17.
There's a dare-I-say “hackish” way to fix it with the __VA__OPT__
special token.
This is a special token whose only purpose
is to disappear along with its arguments if there's zero arguments to __VA_ARG__
(i.e. it takes the ball and goes home if there's no-one else to play with).
Hence, we can hide the comma from the syntax parser by putting it inside __VA_OPT__
parentheses.
The final version becomes:
#define yassert(cond, ...) \ ( (cond) || \ aussie_yassert_fail(#cond, __FILE__, __LINE__ \ __VA_OPT__(,) __VA__ARG__) )
Note that the comma after __LINE__
is now inside of a __VA_OPT__
special macro.
Actually, that's not the final, final version. We really should add “__func__
” in there, too, to report
the function name.
Heck, why not add __DATE__
and __TIME__
while we're at it?
Why isn't there a standard __DEVELOPER__
macro that adds my name?
I really need someone from the C++ committee to wash my mouth out with soap.
I mean, __VA_OPT__
is not a hack; it's an internationally standardized feature.
Sorry, my mistake!
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |