std::static_assert中的pow触发错误C2057
std::pow in static_assert triggers error C2057?
Visual Studio 2013中的以下代码导致错误C2057:
#include <cmath>
int main() {
static_assert(std::pow(2, 2) < 5, "foobar");
return 0;
}
错误C2057:应为常量表达式
如果我在GCC -std=c++0x
下编译,它工作得很好。http://ideone.com/2c4dj5
如果我用4
替换std::pow(2, 2)
,它也会在Visual Studio 2013下编译。
- 这是VS2013错误吗
- 我该如何解决这个问题
std::pow
不是constexpr
函数。GCC之所以接受您的代码,是因为它提供了pow
的内置版本,该版本在编译时评估函数,因为参数是已知的。如果在GCC命令行中添加-fno-builtin
标志,则代码编译失败。错误消息如预期:
错误:静态断言的非恒定条件
因此,这不是VS2013错误,而是GCC优化的效果。clang也不编译代码。
解决方法是将自己的pow
实现为constexpr函数。
template<typename T>
constexpr T _pow(T x, size_t y) {
return y ? x * _pow(x, y-1) : 1;
}
这个实现非常简单,但应该可以在您的用例中使用。
相关文章:
- 在C++中如何在没有pow的情况下进行基础计算
- 理解GCC中的std::pow实现
- 子例程,不使用 pow,并带有参数和返回
- 整数溢出,最大值为 pow(10,19)
- 在 while 循环中使用 pow() 函数 C++
- 在C++不使用 POW 的情况下处理负指数
- C++ 中 pow() 函数的输出没有给出准确的答案
- 没有匹配'pow'功能
- 为什么 while ((i <= 9) && square == pow(i, 2)) { cou
- Arduino Pow() 和 Armstrong 数问题
- C++在不使用pow或循环的情况下计算一个数字的幂
- 让constexpr在OSX上的C++17中使用pow
- Why (int)pow(2, 32) == -2147483648
- 错误:"int pow(double,int)"与上一个声明int pov(double a,int
- Pow 在 C++ 中无法按预期工作
- C++使用负矢量大小计算的 pow 行为
- 在C++中使用 pow() 时出错
- 如何修复 E2015 "ambiguity between pow(double,double) and pow(float,int)"
- constexpr exp, log, pow
- std::static_assert中的pow触发错误C2057