我最近开始阅读 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 行*/ } 主函数() { 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 行 */ }
它按预期工作。我不明白。