Search code examples
c++c++11static-assert

C++ : compile time assert the value of a floating point number


I am using C++ 11. I have a floating point number.

float some_float = 3.0;

Now I want to compile time check that this number is greater than some value. Say that I want to compile time assert that some_float is greater than 1.0. i am trying this:

static_assert(some_float > 1.0);

But, it errors out complaining,

error: static_assert expression is not an integral constant expression
static_assert(some_float > 1.0);
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Question:
what is wrong that I am doing?
How can I assert at compile time that some_float is set to something above 1.0?


Solution

  • some_float must be constexpr

    constexpr float some_float = 3.0;
    

    If you define some_float simply as float, can be used in an assert(), that works runtime; not in a static_assert(), that is checked compile time.

    Moreover: in C++11 it's required a string for an error message

    static_assert ( some_float > 1.0f , "!" );  
    //..................................^^^ error message