C++将工会转换为整数
我有2种类型的别名:
struct A { uint64_t i; };
struct B { uint64_t j; };
a
和b
不是相同的类型,并且不是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个基类,例如: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.