Reputation: 23135
I'm just curious about boost::variant
's implementation.
Does it work like this?
Two members:
apply_visitor()
:
Has a switch
statement on the number representing the currently stored type to call the correct overload (this would in the worse case be compiled as jump table so take constant time).
I understand there's also there are a number of optimisations which can sure boost::variant
does not need to dynamically allocate memory as detailed here, but I think I get these.
Upvotes: 9
Views: 2841
Reputation: 10348
It works pretty much the way you described. Long story short:
It has an integer which
that indicates which data type is used.
The storage is implemented using boost's aligned_storage
which basically is a buffer of the maximum data size. (it is in a union, but for alignment purposes)
Finally, the visitor is indeed implemented with a switch
, generated at compile time using macros to unroll for all type possibilities.
Upvotes: 7