【问题标题】:initialize an array of std::byte with integer type用整数类型初始化 std::byte 数组
【发布时间】:2021-06-10 02:06:20
【问题描述】:

我有一个

typedef std::array<std::byte, 4> CatType;

我想初始化一个这种类型的常量。我可以的

const CatType mycat = {std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}};

这很有效,但我想要类似的可读性

const CatType mycat = 0x001020ff

失败并出现错误

conversion from ‘int’ to non-scalar type ‘const CatType’ {aka ‘const std::array<std::byte, 4>’} requested

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    您可以将CatType 定义为包装类而不是typedef,并从int 定义转换构造函数:

    #include <array>
    #include <cstddef>
    
    class CatType {
        private:
            std::array<std::byte, 4> m_arr;
    
        public:
            CatType(int value) :
                m_arr {
                    std::byte((value >> 24) & 255),
                    std::byte((value >> 16) & 255),
                    std::byte((value >> 8) & 255),
                    std::byte(value & 255),
                }
            {
    
            }
    
            std::byte& operator [](std::size_t index) {
                return m_arr[index];
            }
            std::byte operator [](std::size_t index) const {
                return m_arr[index];
            }
    };
    

    如果您不想创建包装类,user-defined literal(自 C++11 起可用)是您可以获得的最接近的类:

    #include <array>
    #include <cstddef>
    
    std::array<std::byte, 4> operator ""_arr(unsigned long long value) {
        return std::array<std::byte, 4> {
            std::byte((value >> 24) & 255),
            std::byte((value >> 16) & 255),
            std::byte((value >> 8) & 255),
            std::byte(value & 255)
        };
    }
    
    // Usage:
    typedef std::array<std::byte, 4> CatType;
    int main() {
        const CatType mycat = 0x001020ff_arr;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-11
      • 2023-03-06
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2017-05-17
      相关资源
      最近更新 更多