| Start |
|---|
Trivial use of X-macros for printfs This example will result in the preprocessor generating the following code: |
| Extension: Give the X macro as an argument The X-macro approach can be generalized a bit by making the name of the "X" macro an argument of the master macro. This has the advantages of helping to avoid macro name collisions and of allowing use of a general-purpose macro as the "X" macro. As always with X macros, the master macro represents a list of items whose significance is specific to that macro. In this variation, such a macro might be defined like so: One might then generate code to print the item names like so: That expands to this code: In contrast to standard X macros, where the "X" name is a built-in characteristic of the master macro, with this style it may be unnecessary or even undesirable to afterward undefine the macro used as the argument ( |
Enum Value and Identifier Next you can use the enumerated value in your code and easily print its identifier using : |
| Code generation X-Macros can be used for code generation, by writing repetitive code: iterate over a list to do some tasks, or to declare a set of constants, objects or functions. Here we use X-macros to declare an enum containing 4 commands and a map of their names as stringsThen we can print the string values of the enum. Similarly, we can generate a jump table to call functions by the enum value.This requires all functions to have the same signature. If they take no arguments and return an int, we would put this in a header with the enum definition: All of the following can be in different compilation units assuming the part above is included as a header: An example of this technique being used in real code is for GPU command dispatching in Chromium. RemarksThe user of an X-macro-style master macro is expected to provide his own definition for the inner Additionally, by redefining Although the "X-macro" name comes from the traditional name of the inner macro, the technique does not depend on that particular name. Any valid macro name can be used in its place. Criticisms include
A good explanation of X macros can be found in Randy Meyers' article [X-Macros] in Dr. Dobbs (http://www.drdobbs.com/the-new-c-x-macros/184401387) (opens new window)). |
Read Article
https://develop.horje.com/learn/1434/reference