Some tips and typical use case senorios about the macro using of the c/cpp
Both the macros and templates can be used to generate the new code based on some meta programming, generally speaking, there is no type checking for the template, and there are more flexibility (error-prone) for the macro, the macro can be viewed as a generalized techniques for the text substitution. One of the core reason is that, the code that you write is not the code that the code for the compiler.
The use case senorios of the macro is more variant compared with the template, and for the large scale projects, multiple classes may contains similar code, and the macro is definately a suitable choice.
some basic knowledge
variadic macros
this is example about the varadic macro
#define CHECK1(x, ...) if (!(x)) { printf(__VA_ARGS__); } |
##
and #
operator
the #
is often called Stringizing operator, and the following preprocessor turns the line printf(mkstr(geeksforgeeks))
; into printf(“geeksforgeeks”)
;
// CPP program to illustrate (#) operator |
##
is often called Token-pasting operator, 这个operator可以用来连接两个前后两个参数,把它们变成一个字符串。 If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed.
The preprocessor transforms printf(“%d”, concat(x, y))
; into printf(“%d”, xy)
// CPP program to illustrate (##) operator |
some use cases
debug log
use the macro as the debug, namely the debug macro
this is an example:
https://wangzhezhe.github.io/2020/08/05/c:cppdebug-macro/
get and set
vtk example
For example in the VTK library, the Common/Core/vtkSetGet.h file (https://github.com/Kitware/VTK/blob/master/Common/Core/vtkSetGet.h) contains los of different macros, we could see several examples of how will the macro used in large project in general, the commonly used case is thevtkGetObjectMacro
that return the paticular instance in a class or the type macro that specify the relationship between the current class and the parent class.
function/class register
provide an register interface for the commonly used function such as the put and get for the particular variable.
references
good explanation
https://docs.microsoft.com/en-us/cpp/preprocessor/macros-c-cpp?view=msvc-160
https://www.geeksforgeeks.org/and-operators-in-c/
https://stackoverflow.com/questions/180320/are-c-templates-just-macros-in-disguise