# MSVC 2015 constexpr and static assertion

This topic is 672 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

C++11 constexpr doesn't allow to use a static_assert to check the argument of a constexpr function ; C++11 doesn't actually allow a lot of things beside return statement in constexpr function, and while static_assert is allowed in a constexpr function body it can't access the function input.

Which means something like :

constexpr int f(int x)
{
static_assert(x > 0);
return (x > 2) ? x + 1 : x - 3;
}


won't compile because x is an argument of f and not some template arg.

It makes sense from a formal point of view since a constexpr function can be called with non constexpr argument and thus evaluated at runtime.

But from a practical point of view this means that some template construct are required to implement compile time argument checks, and the idea behind constexpr is to alleviate struggle when doing meta programming by providing a more lightweight syntax.

Is there some alternative way to have compile time check inside a constexpr expression ? With Google I found that throwing exception can cause a compile time error but I had no luck with MSVC2015 : it throws when I start my app but it still builds...

Vincent

##### Share on other sites
Some possibly useful stuff: http://stackoverflow.com/questions/1980012/boost-static-assert-without-boost

Just throwing it out there. Not sure if it actually suits your purposes. The problem is that constexpr is, particularly in C++11, pretty crippled. The standards committee has stated that they plan on slowly adding to it over time.

##### Share on other sites

Its not just consexpr limitations on the function that causes problems here. static_assert expects the first parameter to be a boolean constant expression (to include any expression that can be statically-known at compile-time, not just constexpr) -- in the case that function f would be evaluated at runtime, what is the compiler to do with that static_assert? If f is not constexpr, then x was not known at compile time, and still the code tries to feed it to static_assert which needs it to be const. The two cannot co-exist in this way.

What you probably want, is for the static_assert to be dropped out of runtime-evaluated constexpr functions, but that's not how it works.