5

我最近开始阅读 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 行 */ }

它按预期工作。我不明白。

4

2 回答 2

2

尝试Loki 库中的更新版本

于 2010-10-14T15:52:11.783 回答
0

由于 C++11,最好使用static_assert而不是这种技术。现代 C++ 设计中描述的许多内容现在已被标准语言或库功能所取代。它(可能)仍然值得一读。

于 2021-04-06T10:31:58.557 回答