积分推广与运营商+=

Integral promotion and operator+=

我需要消除 gcc -Wconversion 警告。例如

typedef unsigned short     uint16_t;

uint16_t a = 1;
uint16_t b = 2;
b += a;

给予

warning: conversion to 'uint16_t {aka short unsigned int}' from 'int' may alter its value [-Wconversion]
     b += a;
     ~~^~~~

我可以通过

消除它
uint16_t a = 1;
uint16_t b = 2;
b = static_cast<uint16_t>(b + a);

有没有办法保留operator+=并消除警告?谢谢。

编辑

我用

gcc test.cpp -Wconversion

我的 gcc 版本是

gcc.exe (Rev3, Built by MSYS2 project) 7.2.0

I need to eliminate gcc -Wconversion warnings.

你没有说为什么,但这实际上不太可能。

来自the GCC wiki page on this switch

Why isn't Wconversion enabled by -Wall or at least by -Wextra?

Implicit conversions are very common in C. This tied with the fact that there is no data-flow in front-ends (see next question) results in hard to avoid warnings for perfectly working and valid code. Wconversion is designed for a niche of uses (security audits, porting 32 bit code to 64 bit, etc.) where the programmer is willing to accept and workaround invalid warnings. Therefore, it shouldn't be enabled if it is not explicitly requested.

如果你不想要它,就把它关掉。

用不必要的转换破坏代码,使其更难阅读和维护,是错误的解决方案。

如果您的构建工程师坚持使用此标志,请询问他们为什么,并要求他们停止。

您可以构建自己的抽象来重载 += 运算符,例如

template <typename T>
class myVar {
    public:
    myVar(T var) : val{var} {}
    myVar& operator+=(const myVar& t) { 
        this->val = static_cast<T>(this->val + t.val);
        return *this; 
    }
    T val;
};

int main()
{
    typedef unsigned short     uint16_t;

    myVar<uint16_t> c{3};
    myVar<uint16_t> d{4};
    c += d;
}

它仍然使用一个static_cast,但你只需要使用一次,然后再使用它。而且您的 main.

中不需要它

恕我直言,它只是增加了开销,但意见可能会有所不同...