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

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.


Throwing an exception might be useful as the compiler will ignore the run-time part when it knows at compile-time that the exception is not thrown.

#include <cassert>

constexpr int getClamped(int mValue, int mMin, int mMax)
{
    return ( mMin <= mMax ) ? 
           ( mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue) ) :
           throw "mMin must be less than or equal to mMax";
}

int main( int argc, char** argv )
{
    // These two work:
    static_assert( getClamped( 42, 0, 100 ) == 42, "CT" );
    assert( getClamped( argc, 0, 100 ) == argc );

    // Fails at compile-time:
    // static_assert( getClamped( 42, 100, 0 ) == 42, "CT" );

    // Fails at run-time:
    // assert( getClamped( argc, 100, 0 ) == argc );
}

Live example