2

I want to use an std::array of std::byte to store a binary message.

#include <cstddef>
#include <array>

int main() {
    std::byte b {42};                       // OK
    std::array<std::byte, 2> msg {42, 43};  // Compilation Error
}

I'm getting the following error:

<source>: In function 'int main()':
<source>:6:35: error: cannot convert 'int' to 'std::byte' in initialization
    6 |     std::array<std::byte, 2> msg {42, 43};
      |                                   ^~
      |                                   |
      |                                   int

Why I'm getting this error and how to fix it?

Aamir
  • 1,974
  • 1
  • 14
  • 18
  • 1
    Use `static_cast`. – 273K Nov 13 '22 at 19:15
  • 2
    `std::byte b = 42` would fail, too. it's meant to be a very distinct type from ints. – apple apple Nov 13 '22 at 19:16
  • I think that there is no implicit constructor for `std::byte` from `int`, so you need to construct it explicitly – complikator Nov 13 '22 at 19:19
  • 2
    `std::byte` can be [initialized directly from an integer](https://en.cppreference.com/w/cpp/language/enum#enum_relaxed_init_cpp17) only if done through list initalization, not through aggregate initialization of an outer type. Try `std::array msg {std::byte{42}, std::byte{43}}` – Remy Lebeau Nov 13 '22 at 19:20
  • @273K , if `array` size is big then using `static_cast` for each element will be very cumbersome. I think `std::byte` is not ideal for storing binary message. I wonder what is the purpose of `std::byte` then. – Aamir Nov 13 '22 at 19:23
  • 2
    @Aamir `std::byte` is fine for binary messages. You don't need to initialize the contents of the `std::array` directly in its declaration, you can fill the bytes afterwards as needed, for instance by using `std::memcpy()` to copy bytes from other binary variables. – Remy Lebeau Nov 13 '22 at 19:24
  • 1
    You can potentially create an `array` then `bit_cast`: `std::bit_cast>(std::to_array({42, 43}))` – Ranoiaetep Nov 13 '22 at 19:38
  • 2
    `std::byte operator "" _by(unsigned long long x) { return static_cast(x); } std::array x = { 42_by, 43_by };` – n. m. could be an AI Nov 13 '22 at 20:11

0 Answers0