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

后端 未结 8 644
无人共我
无人共我 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:02

    Narrowing conversion errors interact badly with implicit integer promotion rules.

    I had an error with code which looked like

    struct char_t {
        char a;
    }
    
    void function(char c, char d) {
        char_t a = { c+d };
    }
    

    Which produces an narrowing conversion error (which is correct according to the standard). The reason is that c and d implicitly get promoted to int and the resulting int isn't allowed to be narrowed back to char in an initializer list.

    OTOH

    void function(char c, char d) {
        char a = c+d;
    }
    

    is of course still fine (otherwise all hell would break loose). But surprisingly, even

    template
    void function() {
        char_t a = { c+d };
    }
    

    is ok and compiles without a warning if the sum of c and d is less than CHAR_MAX. I still think this is a defect in C++11, but the people there think otherwise - possibly because it isn't easy to fix without get rid of either implicit integer conversion (which is a relict from the past, when people wrote code like char a=b*c/d and expected it to work even if (b*c) > CHAR_MAX) or narrowing conversion errors (which are possibly a good thing).

提交回复
热议问题