C++:编译时断言浮点数的值

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

本文关键字:浮点数 断言 编译 C++      更新时间:2023-10-16

我正在使用C++ 11。我有一个浮点数。

float some_float = 3.0;

现在我想编译时间检查这个数字是否大于某个值。假设我想编译时间断言some_float大于1.0。我正在尝试这个:

static_assert(some_float > 1.0);

但是,它错误地抱怨,

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

问题:
我做错了什么?
如何在编译时断言some_float设置为高于 1.0 的值?

some_float必须constexpr

constexpr float some_float = 3.0;

如果你简单地将some_float定义为float,则可以在运行时工作的assert()中使用,而不是在static_assert()中,即检查编译时。

此外:在 C++11 中,错误消息需要一个字符串

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