Narrowing conversions in C++0x. Is it just me, or does this sound like a breaking change?

后端 未结 8 600
无人共我
无人共我 2020-11-27 14:21

C++0x is going to make the following code and similar code ill-formed, because it requires a so-called narrowing conversion of a double to a int<

相关标签:
8条回答
  • 2020-11-27 15:14

    I ran into this breaking change when I used GCC. The compiler printed an error for code like this:

    void foo(const unsigned long long &i)
    {
        unsigned int a[2] = {i & 0xFFFFFFFF, i >> 32};
    }
    

    In function void foo(const long long unsigned int&):

    error: narrowing conversion of (((long long unsigned int)i) & 4294967295ull) from long long unsigned int to unsigned int inside { }

    error: narrowing conversion of (((long long unsigned int)i) >> 32) from long long unsigned int to unsigned int inside { }

    Fortunately, the error messages were straightforward and the fix was simple:

    void foo(const unsigned long long &i)
    {
        unsigned int a[2] = {static_cast<unsigned int>(i & 0xFFFFFFFF),
                static_cast<unsigned int>(i >> 32)};
    }
    

    The code was in an external library, with only two occurrences in one file. I don't think the breaking change will affect much code. Novices might get confused, though.

    0 讨论(0)
  • 2020-11-27 15:14

    A practical instance that I have encountered:

    float x = 4.2; // an input argument
    float a[2] = {x-0.5, x+0.5};
    

    The numeric literal is implicitly double which causes promotion.

    0 讨论(0)
提交回复
热议问题