Question

The following code in Visual Studio 2013 causes an error C2057:

#include <cmath>

int main() {
    static_assert(std::pow(2, 2) < 5, "foobar");
    return 0;
}

error C2057: expected constant expression

If I compile under GCC -std=c++0x it works fine. http://ideone.com/2c4dj5

If I replace the std::pow(2, 2) with 4, it also compiles under Visual Studio 2013.

  • Is this a VS2013 bug?
  • How can I work around this?
Was it helpful?

Solution

std::pow is not a constexpr function. The reason GCC accepts your code is because it offers a builtin version of pow, which evaluates the function at compile time since the arguments are known. If you add the -fno-builtin flag to the GCC command line, your code fails to compile. The error message is as expected:

error: non-constant condition for static assertion

So, this is not a VS2013 bug, but the effect of a GCC optimization. clang doesn't compile the code either.

OTHER TIPS

The workaround is to implement your own pow as a constexpr function.

template<typename T>
constexpr T _pow(T x, size_t y) {
    return y ? x * _pow(x, y-1) : 1;
}

This implementation is very simple, but should work in your use-case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top