Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use static_assert for constexpr function arguments in C++?

I have several brief constexpr functions in my libraries that perform some simple calculations. I use them both in run-time and compile-time contexts.

I would like to perform some assertions in the body of these functions, however assert(...) is not valid in a constexpr function and static_assert(...) can not be used to check function parameters.

Example:

constexpr int getClamped(int mValue, int mMin, int mMax) noexcept
{
    assert(mMin <= mMax); // does not compile!
    return mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue);
}

Is there a way to check whether the function is being executed in a run-time or compile-time constant and execute the assert only if it's being executed at run-time?

constexpr int getClamped(int mValue, int mMin, int mMax) noexcept
{
    assert_if_runtime(mMin <= mMax); 
    return mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue);
}
like image 727
Vittorio Romeo Avatar asked Sep 27 '14 08:09

Vittorio Romeo


1 Answers

assert works now that g++ has implemented N3652, Relaxing constraints on constexpr functions. This status page indicates that this has been implemented in gcc5.

assert also works (in constexpr functions) on the current clang compiler shipped by Apple, with -std=c++1y.

At this time, I see nothing in the standard that assures one that assert will work in constexpr functions, and such an assurance would be a welcome addition to the standard (at least by me).

Update

Richard Smith drew my attention to LWG 2234 submitted by Daniel Krügler which is attempting to create the assurance I refer to above. This has been incorporated into C++17.

like image 169
Howard Hinnant Avatar answered Oct 09 '22 22:10

Howard Hinnant