Reputation: 327
Are there any use cases where a union must be used and boost::variant cannot be used?
More specifically: Are there any problems which unions can solve and boost::variant can't?
As C++ standard committee recommends using variant instead of union .
Upvotes: 0
Views: 475
Reputation: 393124
Although unions technically allow some things that variants would not, in practice those things are Undefined Behaviour.
Note that this is a lot stronger than Implementation Defined: you cannot depend on the same compiler doing the same thing twice, or a future version of the compiler doing the same thing.
In terms of portability, there would be none, because UB means "anything can happen".
The fact that some compilers treat it as Implementation Defined for now is really just a side note in the scope of Standard C++
Variants aim to make the discriminated union (tuple(union, discriminant)
) safe, a bit like array_view is designed to make tuple(pointer, size)
safe.
Upvotes: 2