C++11 - static_assert within constexpr function?

c++, c++11, constexpr, static-assert

Solution

This is not valid C++11 code, because a constexpr function must only contain a return statement.

This is incorrect. `static_assert` in a `constexpr` function are fine. What is not fine is using function parameters in constant expressions, like you do it.

You could throw if `x <= 0`. Calling the function in a context that requires a constant expression will then fail to compile

constexpr int do_something(int x) {
  return x > 0 ? (x + 5) : (throw std::logic_error("x must be > 0"));
}

Problem

How would one properly do a `static_assert` within a `constexpr` function? For example: ``` constexpr int do_something(int x) { static_assert(x > 0, "x must be > 0"); return x + 5; } ``` This is not valid C++11 code, because a constexpr function must only contain a return statement. I don't think that the standard has an exception to this, although, the GCC 4.7 does not let me compile this code.

Original source