c++ - 模板和#defines 的奇怪行为

标签 c++ templates visual-studio-2008 syntax c-preprocessor

我有以下定义:

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/

相关文章:

c++ - 如何转发声明依赖于变体定义的类,而变体定义又依赖于模板化类?

c++ - 作用域指针和重置

c++ - make 中的 GAlib247 错误

指向具有(虚拟)继承的模板类的 C++ 指针

Django 模板 : how to show dict whose key has a dot in it? d ['key.name' ]

c++ - 错误 4 错误 C3861 : 'snprintf' : identifier not found

c++ - 如何组合加密哈希?

c++ - Variadic 模板包装函数调用

c++ - 提高 SQLite SELECT 性能

visual-studio - Visual Studio 中的缓慢调试问题