Is it legal for a function-like macro to “comma” commas from a list of template arguments in parentheses?

I was just surprised that providing a type with two template arguments to a function-like macro led to a compiler complaint.

This (conceptually similar) sample code:

template<typename T>    struct foo{};
template<typename T, U> struct bar{};
#define p(x) printf("sizeof(" #x ") = %u\n", sizeof(x));

int main()
{
   p(foo<int>);        // works, of course
   p(bar<int,int>);    // does not work
   p((bar<int,int>));  // does not work either
   return 0;
}

makes GCC (6.2.0) a complaint macro "p" passed 2 arguments, but takes just 1.

Well, of course, a preprocessor is a preprocessor that performs text replacement, it is not a true C ++ compiler that understands patterns or all other language rules.

Maybe I ask too much, expecting the preprocessor to recognize the angle brackets provided ... but at least the parentheses are explicitly mentioned in the specification.

16.3 ( 10-12) , . "outermost" , ( ) , .
, " ", " " - , , .

?

+4
1

p((bar<int,int>)) p , (bar<int,int>). .

, sizeof((bar<int,int>)), sizeof .

(++ 11) .

#define p(...) printf("sizeof(" #__VA_ARGS__ ") = %u\n", sizeof(__VA_ARGS__));
+6

Source: https://habr.com/ru/post/1660330/


All Articles