C++将工会转换为整数

发布于 2025-01-22 07:13:55 字数 1046 浏览 2 评论 0原文

我有2种类型的别名:

struct A { uint64_t i; };
struct B { uint64_t j; };

ab不是相同的类型,并且不是uint64_t主要出于可读性原因。它们表示固有不同的程序资源的ID(例如a表示图像的ID,b表示原始缓冲区的ID)。

在该计划的大部分时间里,它们都保持分开并做自己的事情,但是在某一时刻,它们需要序列化。为了防止为两者编写相同的逻辑,并防止使用模板(长篇小说),我结合了一个结合:

union ResourceHandle {
    A a;
    B b;
}

说我有这个结构:

struct MetaData
{
    ResourceHandle handle;
    /* other data */
}

我想编写void serialialize(const metadata& data);

i知道句柄是uint64_t,所以我只想通过添加来将联盟施加到这种类型中:

union ResourceHandle
{
    A a;
    B b;
        
    operator uint64_t() const { return a; }
};

我怀疑这是不确定的行为,但是我认为它通常在大多数系统中起作用。有什么方法可以可靠地从Union中可靠地施放到uint64_t而无需使用其他内存来检查两个实际存储的哪个?

I have 2 type aliases:

struct A { uint64_t i; };
struct B { uint64_t j; };

A and B are not the same type, and are not uint64_t primarily for readability reasons. They represent IDs of program resources that are inherently different (e.g. A represents the ID of an image, and B represents the ID of a raw buffer).

For most of the program's lifetime, they are kept separate and do their own thing, however at one point they need to be serialized. To prevent writing identical logic for both, and to prevent using templates (long story), I made a union:

union ResourceHandle {
    A a;
    B b;
}

Say I have this struct:

struct MetaData
{
    ResourceHandle handle;
    /* other data */
}

I want to write void Serialize(const MetaData& data);

I know that the handle is a uint64_t, so I just want to cast the union into this type by adding:

union ResourceHandle
{
    A a;
    B b;
        
    operator uint64_t() const { return a; }
};

I suspect this is undefined behaviour, but I think it will generally work in most systems. Is there a way I can reliably cast from the union into a uint64_t without using additional memory to check which of the two is actually stored?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞎闹 2025-01-29 07:13:56

您可以创建一个基类,例如:struct ID {uint64_t ID; };
并使A和B成为派生的ID类。
最后,您可以序列化基类。

You can create a base class e.g.: struct ID { uint64_t id; };
and make A and B a derived class of ID.
Finally you can serialize the base class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文