Jump to content
  • Advertisement
Sign in to follow this  
vlj

MSVC 2015 constexpr and static assertion

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!