我有以下定义:
template<typename T1, typename T2>
class Test2
{
public:
static int hello() { return 0; }
};
template<typename T>
class Test1
{
public:
static int hello() { return 0; }
};
#define VERIFY_R(call) { if (call == 0) printf("yea");}
有了这些,我尝试编译以下内容:
VERIFY_R( Test1<int>::hello() );
编译正常
VERIFY_R( (Test2<int,int>::hello()) );
这也可以正常编译,请注意调用周围的括号。
VERIFY_R( Test2<int,int>::hello() );
没有括号会产生警告和几个语法错误:
warning C4002: too many actual parameters for macro 'VERIFY_R'
error C2143: syntax error : missing ',' before ')'
error C2059: syntax error : ')'
error C2143: syntax error : missing ';' before '}'
error C2143: syntax error : missing ';' before '}'
error C2143: syntax error : missing ';' before '}'
fatal error C1004: unexpected end-of-file found
这是怎么回事?
这发生在 VS2008 SP1 中。
最佳答案
宏中的逗号可能会产生歧义:一组额外的括号(您的第二个示例)是消除歧义的一种方式。考虑一个宏
#define VERIFY(A, B) { if ( (A) && (B) ) printf("hi"); }
然后你可以写VERIFY( foo<bar, x> y )
.
另一种消除歧义的方法是用
typedef Test1<int,int> TestII;
VERIFY_R( TestII::hello() );
关于c++ - 模板和#defines 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3186243/