The following code compiles fine.
#define CMD_MACRO(pp, cmd) \
{ \
if (pp)\
{ cmd; } \
}
template<class T> void operate_on(T &data, char c) {
data=data+1;
};
int main() {
int book=4;
char c;
CMD_MACRO(book, {
operate_on<int>(book, c);
});
};
Note that the actual macro in my code is more complex, I have given a simplified version which may not make much logical sense
Now, if I add another template parameter in the function it gives compilation error (problem explained in code comment):
template<class T, bool b> void operate_on(T &data, char c) {
data=data+1;
};
int main() {
int book=4;
char c;
CMD_MACRO(book, {
operate_on<int, false>(book, c); /* here the "," between int and
false is being treated
as separating arguments to CMD_MACRO,
instead being part of 'cmd'. Thats strange
because the comma separating book and c is
treated fine as part of 'cmd'. */
});
};
test.cpp:18:6: error: macro "CMD_MACRO" passed 3 arguments, but takes just 2
test.cpp: In function 'int main()':
test.cpp:16: error: 'CMD_MACRO' was not declared in this scope
How to fix the problem (I need to add that extra template parameter to existing code and am getting such an error).
Have you tried:
(operate_on<int, false>(book, c));? (Notice the extra parentheses around the expression).I believe the preprocessor knows nothing of C++ templates, and so treats the
<and>as just any old token. Without the extra parentheses, it treatsoperate_on<intas one argument, andfalse>(book, c)as another.