Question

I'm just curious about boost::variant's implementation.

Does it work like this?

Two members:

  1. A number representing the currently stored type (i.e. 0 for the first template parameter, 1 for the second template parameter etc)
  2. 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.

Was it helpful?

Solution

It works pretty much the way you described. Long story short:

  1. It has an integer which that indicates which data type is used.

  2. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top