我需要创建一个由constexpr结构体中的字节组成的constexpr数组。
但这不是我需要的。有没有办法做到这一点?
#include <array>
template<typename T>
constexpr std::array<uint8_t, sizeof(T)> o2ba(const T o) {
return {};
}
struct A {
int a;
};
int main() {
constexpr A x{ 1 };
constexpr auto y = o2ba(x); // y == { 0x01, 0x00, 0x00, 0x00 } for little endian
return 0;
}
我试图从联合体中提取它:
template<typename T>
union U {
T o;
std::array<uint8_t, sizeof(T)> d;
};
template<typename T>
constexpr std::array<uint8_t, sizeof(T)> o2ba(const T o) {
return U<T>{o}.d;
}
但是在访问d而不是初始化的o成员时,它会在gcc和msvc编译器上失败。然而,当初始化非constexpr对象时,它可以正常工作,如下所示。
int main() {
constexpr A x{ 1 };
auto y = o2ba(x); // y == { 0x01, 0x00, 0x00, 0x00 } for little endian
return 0;
}
但这不是我需要的。有没有办法做到这一点?
constexpr
上下文中都是不允许的。 - oisyn