c++c++20bit-cast

Syntax for std::bit_cast to an array


#include <bit>
#include <array>

struct A {
    int a[100];
};
struct B {
    short b[200];
};

void test(const A &in) {
    const auto x = std::bit_cast<short[200]>(in); // error: no matching function for call to 'bit_cast<short int [200]>(const A&)
    const auto y = std::bit_cast<B>(in); // OK
    const auto z = std::bit_cast<std::array<short, 200>>(in); // OK
}

The initialization of x is not working, I am curious if there is a syntax to std::bit_cast to an array without extra struct, std::array, memcpy or similar helper functions.

Thanks.


Solution

  • Not even std::bit_cast can return an array, so wrapping in a class (perhaps std::array) is the best you can do.