'C++ convert a union into an integer
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
