简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM