来自现代C&x2B的CompileTimeChecker+;设计未按预期工作 我最近开始阅读Andrei Alexandrescu的现代C++设计。在阅读编译时断言之后,我尝试了以下代码: 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*/ } 模板结构编译器 { CompileTimeChecker(…){}; }; 模板结构CompileTimeChecker{}; #定义静态检查(expr,msg)\ {\ 类错误u##msg{}\ (void)sizeof(CompileTimeChecker((ERROR####msg());/*行1*/} int main() { 静态检查(sizeof(char)>sizeof(int),typetoonearow);/*第2行*/ StaseOpChest[sichOf(char)< p>从.< /p>

来自现代C&x2B的CompileTimeChecker+;设计未按预期工作 我最近开始阅读Andrei Alexandrescu的现代C++设计。在阅读编译时断言之后,我尝试了以下代码: 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*/ } 模板结构编译器 { CompileTimeChecker(…){}; }; 模板结构CompileTimeChecker{}; #定义静态检查(expr,msg)\ {\ 类错误u##msg{}\ (void)sizeof(CompileTimeChecker((ERROR####msg());/*行1*/} int main() { 静态检查(sizeof(char)>sizeof(int),typetoonearow);/*第2行*/ StaseOpChest[sichOf(char)< p>从.< /p>,c++,templates,compile-time,C++,Templates,Compile Time,从C++ 11开始,最好使用 StistaSypRe>/Cube >,而不是这种技术。现在很多C++语言设计中所描述的内容已经被标准语言或库特征所取代。(可能)仍然值得一读。精确复制(同一用户):关闭另一个作为副本。让这个打开。@Paul R:我认为@Saurabh发布了两次相同的问题(我认为是错误的),另一个副本已作为此副本关闭,现在您关闭此副本时,会将此副本视为另一个副本的副本。@Prasoon:当我投票关闭此副本时,两个副本都仍然打开-通常新的副本已关闭,但我想只要只有一个副本就行了rem

从C++ 11开始,最好使用<代码> StistaSypRe>/Cube >,而不是这种技术。现在很多C++语言设计中所描述的内容已经被标准语言或库特征所取代。(可能)仍然值得一读。

精确复制(同一用户):关闭另一个作为副本。让这个打开。@Paul R:我认为@Saurabh发布了两次相同的问题(我认为是错误的),另一个副本已作为此副本关闭,现在您关闭此副本时,会将此副本视为另一个副本的副本。@Prasoon:当我投票关闭此副本时,两个副本都仍然打开-通常新的副本已关闭,但我想只要只有一个副本就行了remains@Nikolai:这样行。在那个代码中,是什么这就是(void)Error_##msg的必要性;我猜第二条语句就在那里,所以编译器不会抱怨未使用的变量。好的。关于我实际提出的问题,您有什么意见吗?GCC 4.2.1说:
Error:sizeof对函数类型的无效应用
关于
main()中的两行
,即扩展宏被解释为函数声明。这也是我链接的代码中的注释所建议的。您的编译器可能只是在欺骗和跳过(…)的
(void)sizeof
line。此外,洛基库——书中的所有代码以及更多内容——在写这本书时,任何现有的编译器都无法完全编译。 (void)(CompileTimeChecker<(expr)!=0>((ERROR_##msg()))); /*Line 1*/ } new CompileTimeChecker<(expr)!=0>((ERROR_##msg())); /* Line 1*/ }