代码之家  ›  专栏  ›  技术社区  ›  Pietro

为什么静态断言错误:“表达式必须有一个常量值”,即使我传递常量?

  •  0
  • Pietro  · 技术社区  · 5 年前

    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 10

    1 回复  |  直到 5 年前
        1
  •  0
  •   Pietro    5 年前

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

    #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