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

后端 未结 3 1252
野性不改
野性不改 2020-12-20 13:16

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

3条回答
  •  粉色の甜心
    2020-12-20 13:40

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

提交回复
热议问题