Consider a simple macro:
#define ECHO(x) x
ECHO(foo(1, 2))
This produces the exact output we expect:
foo(1, 2)
The above example works because the parenthesis adjacent to the function call are recognized by the preprocessor.
Now consider what happens if I use a template instead of a function call:
ECHO(template<int, bool>)
This causes an error because the preprocessor interprets the template<int
and the bool>
as two separate arguments to the macro. The preprocessor doesn't recognize <>
for scope!
Is there anyway to use a template like this in a macro?
Macro vs Template Macro are used in C and C++ for replacement of numbers, small inline functions etc. Template is only available in C++ language. It is used to write small macro like functions etc.
The C standard mandates that the only place the identifier __VA_ARGS__ can appear is in the replacement list of a variadic macro. It may not be used as a macro name, macro argument name, or within a different type of macro. It may also be forbidden in open text; the standard is ambiguous.
Macros using #define A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive.
Macro Arguments (DEFINE-! ENDDEFINE command) The macro definition can include macro arguments, which can be assigned specific values in the macro call. There are two types of arguments: keyword and positional. Keyword arguments are assigned names in the macro definition; in the macro call, they are identified by name.
#define COMMA ,
ECHO(template<int COMMA bool>)
A little painful, but it works.
FWIW, if the syntax for the argument allows ()
s, you don't need the substitution, e.g.,
ECHO((a, b))
will work for a single argument macro but that doesn't work in all cases (including yours).
A variadic macro may help:
#define ECHO(x...) x
ECHO(foo(1, 2))
ECHO(template<int, bool>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With