I've seen them used for multiple implementations. Here's a few:
•
Conversions. Because C++'s conversion operators do not allow conversion from a
void pointer (with
reinterpret_cast), a union may be used to perform this cast. For instance:
1 2 3 4 5 6 7 8 9 10 11 12
|
template <typename T>
void *convert_to_voidp(T *pointer)
{
union
{
T *in;
void *out;
} result;
result.in = pointer;
return(result.out);
}
|
C++ restricts conversions to a
void pointer for a reason, so this sort of conversion isn't exactly safe, nor does it make much sense. You'd best have a good reason for using this conversion method. Be sure to favour
static_cast to convert from a
void*.
•
CPU Registers. This sort of union usage is found in kernel implementations. Here's a sample:
1 2 3 4 5 6
|
union cpu_registers
{
short ax; // 16-bit register
int eax; // 32-bit register
long long int rax; // 64-bit register
};
|
•
Variants. Commonly found in scripting languages such as Lua, and Python. Variants allow a variable to store 1 value at a time, but that value can be of multiple types. This usage of unions allow variables to be dynamic, and possibly polymorphic. Here's a sample:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
union variant
{
double double_value;
int int_value;
char char_value;
/* operators... */
};
enum variant_tag
{
DOUBLE,
INT,
CHAR
};
struct dynamic_variable
{
variant value;
variant_tag tag; // Identifies the current value type
};
|
•
I/O Ports. Similar to the CPU registers implementation of the union.
Since unions only reserve enough memory to hold the largest member, it saves memory, unlike a structure which allocates memory for members + alignment padding. There's no other structure in the C/C++ programming language that behaves like a union. Because of this, it's considered unique. Unions are by far one of the most flexible structures in the language. The flexibility of a union depends on the types it supports, and the operators it overloads.
Edit: Typo.
Wazzak