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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With