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

后端 未结 3 1255
野性不改
野性不改 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:38

    A refinement on Daniel Frey's answer is to use noexcept on the constexpr function to turn the runtime error into a call to std::terminate. Assertion failures are unrecoverable; they should halt the process immediately. Turning them into exceptions is a very bad idea.

    #include 
    #include 
    
    struct assert_failure
      : std::logic_error
    {
        explicit assert_failure(const char *sz)
          : std::logic_error(sz)
        {}
    };
    
    constexpr bool in_range(int i, int j, int k) noexcept
    {
        return (i <= j && j <= k) ? true : throw assert_failure("input not in range");
    }
    
    int main(int argc, char* argv[])
    {
        constexpr bool b1 = in_range(0, 4, 5); // OK!
        constexpr bool b2 = in_range(0, 6, 5); // Compile-time error!
        bool b3 = in_range(0, 4, argc);        // May or may not terminate the process
    }
    

    The runtime error for me looks like:

    terminate called after throwing an instance of 'assert_failure'
      what():  input not in range
    Aborted (core dumped)
    

    Hope that helps.

提交回复
热议问题