c++ - 将结构转换为 uint8_t 的 constexpr 数组

标签 c++ arrays templates c++17 constexpr

我需要从 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/

相关文章:

java - 从输入文件中获取值并逐行添加到整数数组中(java)

ios - 不调用索引路径行的空 TableView 单元格

java - Arraylist<String[]> 如何访问?

c++ - 使用可变参数模板重载函数模板 : Intel c++ compiler version 18 produces different result from other compilers. intel 错了吗?

c++ - 从 C++ 中的基方法调用重写的子方法

c++ - 将 vector 从 c++ dll 重新调整到另一个 c++ exe 时出现问题

c++ - 推导使用循环模板的函数的参数

c++ - 使用嵌套映射的可变模板参数推断

c++ - 如何获取 GLFW 窗口 ID?

c++ - 线程池实现