由于我们小组中的某个人讨厌异常(在这里不做讨论),因此我们倾向于在C++项目中使用错误检查宏。使用带有两个类型参数的模板化函数时,我遇到了奇怪的编译失败。有一些错误(如下),但我认为根本原因是警告:
warning C4002: too many actual parameters for macro 'BOOL_CHECK_BOOL_RETURN'
最好用代码解释一下:
#include "stdafx.h"
template<class A, class B>
bool DoubleTemplated(B & value)
{
return true;
}
template<class A>
bool SingleTemplated(A & value)
{
return true;
}
bool NotTemplated(bool & value)
{
return true;
}
#define BOOL_CHECK_BOOL_RETURN(expr) \
do \
{ \
bool __b = (expr); \
if (!__b) \
{ \
return false; \
} \
} while (false) \
bool call()
{
bool thing = true;
// BOOL_CHECK_BOOL_RETURN(DoubleTemplated<int, bool>(thing));
// Above line doesn't compile.
BOOL_CHECK_BOOL_RETURN((DoubleTemplated<int, bool>(thing)));
// Above line compiles just fine.
bool temp = DoubleTemplated<int, bool>(thing);
// Above line compiles just fine.
BOOL_CHECK_BOOL_RETURN(SingleTemplated<bool>(thing));
BOOL_CHECK_BOOL_RETURN(NotTemplated(thing));
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
call();
return 0;
}
以下是未注释掉违规行时的错误:
1>------ Build started: Project: test, Configuration: Debug Win32 ------
1>Compiling...
1>test.cpp
1>c:\junk\temp\test\test\test.cpp(38) : warning C4002: too many actual parameters for macro 'BOOL_CHECK_BOOL_RETURN'
1>c:\junk\temp\test\test\test.cpp(38) : error C2143: syntax error : missing ',' before ')'
1>c:\junk\temp\test\test\test.cpp(38) : error C2143: syntax error : missing ';' before '{'
1>c:\junk\temp\test\test\test.cpp(41) : error C2143: syntax error : missing ';' before '{'
1>c:\junk\temp\test\test\test.cpp(48) : error C2143: syntax error : missing ';' before '{'
1>c:\junk\temp\test\test\test.cpp(49) : error C2143: syntax error : missing ';' before '{'
1>c:\junk\temp\test\test\test.cpp(52) : error C2143: syntax error : missing ';' before '}'
1>c:\junk\temp\test\test\test.cpp(54) : error C2065: 'argv' : undeclared identifier
1>c:\junk\temp\test\test\test.cpp(54) : error C2059: syntax error : ']'
1>c:\junk\temp\test\test\test.cpp(55) : error C2143: syntax error : missing ';' before '{'
1>c:\junk\temp\test\test\test.cpp(58) : error C2143: syntax error : missing ';' before '}'
1>c:\junk\temp\test\test\test.cpp(60) : error C2143: syntax error : missing ';' before '}'
1>c:\junk\temp\test\test\test.cpp(60) : fatal error C1004: unexpected end-of-file found
1>Build log was saved at "file://c:\junk\temp\test\test\Debug\BuildLog.htm"
1>test - 12 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
有任何想法吗?谢谢!
最佳答案
宏不了解该语言,并且只能与词汇标记一起使用。逗号分隔宏的争辩项,因此以下代码尝试使用两个参数来“调用”宏:
BOOL_CHECK_BOOL_RETURN(DoubleTemplated<int, bool>(thing));
DoubleTemplated<int
和bool>(thing)
。那是您所看到的警告,也是其他错误的原因。以下是防止模板参数列表中的,
的正确方法:BOOL_CHECK_BOOL_RETURN((DoubleTemplated<int, bool>(thing)));
关于c++ - 与错误检查宏一起使用时,带有两个类型参数的模板化函数无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62707955/