简体   繁体   中英

Correct way to initialize a container of std::byte

What is the correct way of initializing a container with predetermined std::byte values?

std::array<std::byte, 2> arr{0x36, 0xd0} for array results in

Enum std::byte has not constant to represent the integer value of X

and compiler errors. Vector and initializer lists are a no-go too.

Is std::vector with std::copy and casts really the intended way of handling this?

You will have to write std::byte{0x36} , because there is no implicit conversion from an int to a enum class .

std::array<std::byte, 2> arr = {std::byte{0x36}, std::byte{0xd0}};

If you don't want to write std::byte every single time, write a helper function:

template<typename... Ts>
std::array<std::byte, sizeof...(Ts)> make_bytes(Ts&&... args) noexcept {
    return{std::byte(std::forward<Ts>(args))...};
}

auto arr = make_bytes(0x36, 0xd0);

With C++20, you can utilize to_array to create an array of unsigned char easily, then bit_cast it to an array of byte :

auto arr = std::bit_cast<std::array<std::byte, 2>>(
    std::to_array<unsigned char>({0x36, 0xd0, /*...*/})
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM