Sau*_*nda 5 c++ templates compile-time
我最近开始阅读 Andrei Alexandrescu 的 Modern C++ Design。阅读编译时断言后,我尝试了以下代码:
模板<bool> struct CompileTimeChecker
{
CompileTimeChecker(...){};
};
模板<> struct CompileTimeChecker<false>{};
#define STATIC_CHECK(expr, msg) \
{\
类 ERROR_##msg{}; \
(void)sizeof(CompileTimeChecker<(expr)!=0>((ERROR_##msg()))); /*第1行*/ }
int main()
{
STATIC_CHECK(sizeof(char)>sizeof(int),TypeTooNarrow); /*第2行*/
STATIC_CHECK(sizeof(char)<sizeof(int),TypeTooNarrow); /*第3行*/
}
由于第 2 行,代码不应编译,但编译正常。如果我将第 1 行更改为
(void)(CompileTimeChecker<(expr)!=0>((ERROR_##msg()))); /*第1行*/ }
或者
新的 CompileTimeChecker<(expr)!=0>((ERROR_##msg())); /* 第 1 行 */ }
它按预期工作。我不明白。