I’m just curious about boost::variant‘s implementation.
Does it work like this?
Two members:
- A number representing the currently stored type (i.e. 0 for the first template parameter, 1 for the second template parameter etc)
- A union of all possible types (which of course the size of the largest).
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.
It works pretty much the way you described. Long story short:
It has an integer
whichthat indicates which data type is used.The storage is implemented using boost’s
aligned_storagewhich 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.