我需要从 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;
}
我试图从 union 中提取它:
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;
}
但它在 gcc 和 msvc 编译器上都无法访问 d 而不是已初始化的 o 成员。它在初始化非 constexpr 对象时有效,如下所示。
int main() {
constexpr A x{ 1 };
auto y = o2ba(x); // y == { 0x01, 0x00, 0x00, 0x00 } for little endian
return 0;
}
但这不是我需要的。有办法做到这一点吗?
最佳答案
你想要的是不可能的。在您的代码中,您尝试访问 constexpr
中的初始化成员上下文,这很好。错误是您随后尝试访问非事件成员,这是不允许的 [expr.const#2.8] :
An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:
...
- an lvalue-to-rvalue conversion that is applied to a glvalue that refers to a non-active member of a union or a subobject thereof;
现在,另一种方法是尝试通过 reinterpret_cast
以旧方式将对象序列化为字节。 ,即 reinterpret_cast<const uint8_t*>(&a)
.再次reinterpret_cast
不允许出现在 constexpr
中上下文每 2.15(同一部分)。我怀疑你不能这样做的原因是因为它不可移植。
关于c++ - 将结构转换为 uint8_t 的 constexpr 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48111663/