我如何重新编写代码以避免左移警告?

问题描述 投票:-2回答:1

我具有此方法read,旨在从无符号字符指针data的地址中读取整数数据类型。例如,如果data包含0x12, 0x34, 0x56, 0x78, 0x9A,则read<int>(1, ptrToMyInt)应将0x3456789A放入ptrToMyInt

示例:

class MyClass {
    public:
        MyClass();

        template <typename T> void read(int address, T *dest) {
            size_t size = sizeof(T);

            *dest = 0;

            for (unsigned int i = 0; i < size; i++) {
                *dest <<= 8;
                *dest |= data[address + i];
            }
        }

        static constexpr unsigned char data[] = { 0x12, 0x34, 0x56, 0x78 };
}

[当我在无符号char指针上使用此模板时(出于一致性的考虑,避免使用多个读取方法),它会发出警告,因为*dest <<= 8;行的偏移量超过了字节的宽度,并且编译器并不聪明。足以意识到它仅在字节已经为0时发生一次。

例如:

MyClass c;

unsigned char x;
c.read(2, &x); // warning: shift count >= width of type
               // should and does put 0x56 into x

Demo

我想对这段代码进行重做以避免这种警告,但是我看不到简单/优雅的重写方法。我应该如何重写此代码?

c++ compiler-warnings
1个回答
1
投票

使用C ++ 17,您可能会这样做

template <typename T> void read(int address, T *dest) {
    constexpr size_t size = sizeof(T);

    if constexpr (size == 1)
    {
        *dest = data[address];
    } else {
        *dest = 0;

        for (unsigned int i = 0; i < size; i++) {
            *dest <<= 8;
            *dest |= data[address + i];
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.