Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::variant implementation

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.

like image 826
Clinton Avatar asked Nov 13 '12 02:11

Clinton


People also ask

What is boost :: variant?

Boost. Variant, part of collection of the Boost C++ Libraries. It is a safe, generic, stack-based discriminated union container, offering a simple solution for manipulating an object from a heterogeneous set of types in a uniform manner.

How boost variant works?

In boost::variant , it computes the maximum sized object, and uses "placement new" to allocate the object within this buffer. It also stores the type or the type index. Note that if you have Boost installed, you should be able to see the source files in "any. hpp" and "variant.

What is boost :: Apply_visitor?

boost::apply_visitor — Allows compile-time checked type-safe application of the given visitor to the content of the given variant, ensuring that all types are handled by the visitor.

What is boost :: Static_visitor?

boost::static_visitor is a template. The type of the return value of operator() must be specified as a template parameter. If the operator does not have a return value, a template parameter is not required, as seen in the example. The second parameter passed to boost::apply_visitor() is a boost::variant variable.


1 Answers

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.

like image 104
imreal Avatar answered Sep 21 '22 06:09

imreal