我正在将C++14-constexpr代码库从Clang移植到最新的g++-5.1。考虑以下自Clang3.3的Restful时期以来一直正确编译的本土bitset类的简化代码片段(现在快2年了!)#includetemplateclassbitset;templateconstexprbooloperator==(constbitset&lhs,constbitset&rhs)noexcept;templateclassbitset{friendconstexprbooloperator==(constbitset&,constbitset&)noexcept;//^^^^^^^^^
我似乎发现了Clang和GCC不同意的地方。代码如下:intmain(){ifconstexpr(2){}}使用GCC7.4.0编译成功,但使用Clang7.0.0编译失败,并显示以下错误消息:test.cpp:3:17:error:constexprifconditionevaluatesto2,whichcannotbenarrowedtotype'bool'[-Wc++11-narrowing]ifconstexpr(2){}^1errorgenerated.cppreference似乎没有提到“缩小”,所以这似乎是一个Clang错误,但我并不完全确定。如果这是任一编译器的错误,
我应该在哪里使用macros,我应该在哪里使用constexpr?不是基本一样吗?#defineMAX_HEIGHT720对constexprunsignedintmax_height=720; 最佳答案 Aren'ttheybasicallythesame?没有。绝对不。甚至没有关闭。除了你的宏是一个int而你的constexprunsigned是一个unsigned之外,还有一些重要的区别,宏只有一个优势。范围宏由预处理器定义,每次出现时都简单地替换到代码中。预处理器是哑巴,不理解C++语法或语义。宏会忽略namespace、类
因此注意到pagec++11中的数学函数似乎都没有使用constexpr,而我相信它们都可以。所以这给我留下了两个问题,一个是为什么他们选择不制作函数constexpr。还有两个用于像sqrt这样的函数,我可能会编写自己的constexpr,但是像sin或cos这样的函数会更棘手,所以有办法绕过它。 最佳答案 实际上,由于旧的和烦人的遗留问题,几乎没有一个数学函数可以是constexpr,因为它们都有在各种错误上设置errno的副作用条件,通常是域错误。 关于c++-Consexpr数学