constexpr vs const vs constexpr const

前端 未结 3 1267
小鲜肉
小鲜肉 2021-01-14 13:41

const-vs-constexpr-on-variables

What the guy says about constexpr is right if double is used (or float of course). However, if you change t

3条回答
  •  旧时难觅i
    2021-01-14 13:58

    The compiler does not allow an implicit narrowing or non-integral promotion during the initialisation of a constexpr variable.

    This will work:

    int main()
    {
        const int PI1 = 3;
        constexpr int PI2 = 3;
        constexpr int PI3 = PI1;  // works
        static_assert(PI1 == 3, "");  // works
    
        const double PI1__ = 3;
        constexpr double PI2__ = 3;
        constexpr double PI3__ = double(PI1);  // works with explicit cast
        static_assert(PI2__ == 3, "");  // works now. PI1__ isn't constexpr
        return 0;
    }
    

提交回复
热议问题