Boost :: implementation option

I'm just wondering how to implement boost::variant .

Does it work like this?

Two members:

  • A number representing the current saved type (i.e. 0 for the first template parameter, 1 for the second template parameter, etc.)
  • The union of all possible types (which, of course, is the size of the largest).

apply_visitor() :

It has a switch for a number representing the current stored type to invoke the correct overload (this will be compiled as a jump table in the worst case, so constant time will be required).

I also understand that there are a number of optimizations that can be sure that boost::variant does not need to dynamically allocate memory as detailed here , but I think I get them.

+8
c ++ boost boost-variant
source share
1 answer

It works almost exactly as you described. In short:

  • It has an integer which indicating which data type is being used.

  • The storage is implemented using boost aligned_storage , which is basically a buffer with a maximum data size. (it is in union, but for alignment)

Finally, the visitor is really implemented using the switch generated at compile time using macros to expand for all the features of the type.

+7
source share

All Articles