In our legacy code, as well as our modern code, we use macros to perform nifty solutions like code generations, etc. And we make use of both the #
and ##
operators.
I am curious how other developers use macros to do cool things, if they use them at all.
The BOOST_BINARY macro performs some clevel pre-processor trickery to give C++ the ability to express numeric constants in binary. It is limited to 0-255 however.
One can simplify repetitive things for ie. enum lists
...and later do a switch case over a structured way
Note: Sure this could be done with a function pointer array but this opens for a little more flexibilities to add parameters and also use the string expansions with the single hash.
...or to test on strings to get the right enum value
Most (all?) C++ Unit Testing frameworks are built upon macros. We use UnitTest++. Check it out to see all sorts of fancy macros.
Converting them to a construct of the language to improve type safety and debugging ability.
One of my favorite tricks is a way to pass variable number of arguments to macros, to be later used in calling printf-like functions for example. To do this, I specify that the macro has only one parameter and use it in the body of the macro without (), but pass all the parameters to the macro in (( and )), so the list looks like a single argument. For example,
In C, it's common to define macros that do some stuff getting the verbatim argument, and at the same time define functions to be able to get the address of it transparently.