为什么static_assert错误:即使我确实传递常量,“表达式也必须具有常量值?

问题描述 投票:0回答:1

这段代码编译没有问题:

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

c++ comparison constants static-assert
1个回答
0
投票

有了这个测试程序,我解决了这个问题:

#include <cmath>

constexpr auto val1 = 1.23f;
constexpr auto val2 = HUGE_VALF;

static_assert(val1 == val1, "OK");
static_assert(val2 == val2, "OK");

int main()
{
}

结果:

  • Visual C ++ 2019 32位:确定
  • Visual C ++ 2019 64位:确定
  • Visual C ++ 2013 32位:确定
  • Visual C ++ 2013 64位:失败

输出:

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
© www.soinside.com 2019 - 2024. All rights reserved.