Integral promotion and operator+=

后端 未结 2 1192
孤独总比滥情好
孤独总比滥情好 2021-01-18 04:14

I need to eliminate gcc -Wconversion warnings. For example

typedef unsigned short     uint16_t;

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

gi

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 04:40

    You could build your own abstraction to overload the += operator, something like

    template 
    class myVar {
        public:
        myVar(T var) : val{var} {}
        myVar& operator+=(const myVar& t) { 
            this->val = static_cast(this->val + t.val);
            return *this; 
        }
        T val;
    };
    
    int main()
    {
        typedef unsigned short     uint16_t;
    
        myVar c{3};
        myVar d{4};
        c += d;
    }
    

    It still uses a static_cast, but you only need to use it once and then reuse it. And you don't need it in your main.

    IMHO it just adds overhead, but opinions may vary...

提交回复
热议问题