来自现代 C++ 的 CompileTimeChecker设计未按预期工作
我最近开始阅读 Andrei Alexandrescu 的《Modern C++ Design》。阅读完编译时断言后,我尝试了以下代码:
template<bool> struct CompileTimeChecker { CompileTimeChecker(...){}; }; template<> struct CompileTimeChecker<false>{}; #define STATIC_CHECK(expr, msg) \ {\ class ERROR_##msg{}; \ (void)sizeof(CompileTimeChecker<(expr)!=0>((ERROR_##msg()))); /*Line 1*/ } int main() { STATIC_CHECK(sizeof(char)>sizeof(int),TypeTooNarrow); /*Line 2*/ STATIC_CHECK(sizeof(char)<sizeof(int),TypeTooNarrow); /*Line 3*/ }
由于第 2 行,该代码不应编译,但它编译得很好。如果我将第 1 行更改为
(void)(CompileTimeChecker<(expr)!=0>((ERROR_##msg()))); /*Line 1*/ }
或
new CompileTimeChecker<(expr)!=0>((ERROR_##msg())); /* Line 1*/ }
它会按预期工作。我不明白。
I've recently started reading Modern C++ Design by Andrei Alexandrescu. After reading Compile-Time Assertions, I tried the following code:
template<bool> struct CompileTimeChecker { CompileTimeChecker(...){}; }; template<> struct CompileTimeChecker<false>{}; #define STATIC_CHECK(expr, msg) \ {\ class ERROR_##msg{}; \ (void)sizeof(CompileTimeChecker<(expr)!=0>((ERROR_##msg()))); /*Line 1*/ } int main() { STATIC_CHECK(sizeof(char)>sizeof(int),TypeTooNarrow); /*Line 2*/ STATIC_CHECK(sizeof(char)<sizeof(int),TypeTooNarrow); /*Line 3*/ }
The code should not compile due to Line 2, but it compiles fine. If I change the Line 1 to
(void)(CompileTimeChecker<(expr)!=0>((ERROR_##msg()))); /*Line 1*/ }
or
new CompileTimeChecker<(expr)!=0>((ERROR_##msg())); /* Line 1*/ }
it works as expected. I don't get it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试更新版本来自 Loki 库。
Try updated version from the Loki library.
从 C++11 开始,最好使用
static_assert
而不是这种技术。 《现代 C++ 设计》中描述的许多内容现已被标准语言或库功能所取代。不过,它(可能)仍然值得一读。Since C++11 it's preferable to use
static_assert
rather than this technique. A lot of what is described in Modern C++ Design has now been replaced by standard language or library features. It's (probably) still worth reading though.