I have a example with me where in which the alignment of a type is guaranteed, union max_align . I am looking for a even simpler example in which union is used practically, to explain my friend.
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
I've used sometimes unions this way
Then you could declare arrays of different kind of values, storing more or less efficiently the data, and make some "polimorph" operations like:
For convenience, I use unions to let me use the same class to store xyzw and rgba values
In the Windows world,
unions
are commonly used to implement tagged variants, which are (or were, before .NET?) one standard way of passing data between COM objects.The idea is that a
union
type can provide a single natural interface for passing arbitrary data between two objects. Some COM object could pass you a variant (e.g. typeVARIANT
or_variant_t
) which could contain either adouble
,float
,int
, or whatever.If you have to deal with COM objects in Windows C++ code, you'll see variant types all over the place.
lex
toyacc
. (yylval
)Example:
When using different socket types, but you want a comon type to refer.