这段代码编译没有问题:
const int tmp1 = 1, tmp2 = 1;
const bool cmp = (tmp1 == tmp2);
static_assert(cmp, "OK");
这个也很好:
const bool cmp = (HUGE_VALF == HUGE_VALF);
static_assert(cmp, "OK");
这不是:
const auto tmp = HUGE_VALF;
const bool cmp = (tmp == tmp);
static_assert(cmp, "OK"); // <-- error
错误:表达式必须具有恒定值。变量“ cmp”的值不能用作常量
与static const
的行为相同。
怎么了? HUGE_VALF
是预处理器宏,即常量,而cmp
无疑是编译时间常量...
环境:Microsoft Windows 10Microsoft Visual C ++ 2013和2019
有了这个测试程序,我解决了这个问题:
#include <cmath>
constexpr auto val1 = 1.23f;
constexpr auto val2 = HUGE_VALF;
static_assert(val1 == val1, "OK");
static_assert(val2 == val2, "OK");
int main()
{
}
结果:
输出:
1> TestConstexpr.cpp(5): error C2144: syntax error : 'auto' should be preceded by ';'
1> TestConstexpr.cpp(5): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1> TestConstexpr.cpp(6): error C2144: syntax error : 'auto' should be preceded by ';'
1> TestConstexpr.cpp(6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1> TestConstexpr.cpp(6): error C2086: 'int constexpr' : redefinition
1> TestConstexpr.cpp(5) : see declaration of 'constexpr'
1> TestConstexpr.cpp(8): error C2057: expected constant expression
1> TestConstexpr.cpp(9): error C2057: expected constant expression