std::static_assert中的pow触发错误C2057

std::pow in static_assert triggers error C2057?

本文关键字:C2057 pow 错误 中的 static assert std      更新时间:2023-10-16
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;
}

这个实现非常简单,但应该可以在您的用例中使用。