I have a boost::variant in my program and I want to check if the variant itself is initialized and also if there is a value contained in one of it's types.
I've tried empty() on the variant, but that doesn't seem to work. Neither does checking against NULL.
Does anybody know how to check for this?
EDIT: Ok, It seems it will never be empty, but there will not always be a value in it's contained types, so how do I check for a no-value situation?
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.
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.
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.
The boost::any class (based on the class of the same name described in "Valued Conversions" by Kevlin Henney, C++ Report 12(7), July/August 2000) is a variant value type based on the second category. It supports copying of any value type and safe checked extraction of that value strictly against its type.
if you see my question regarding never empty guarantee and single storage, boost::variant
does support a NIL-like value type called boost::blank
. which will guarantee that variant never uses the heap as backup storage
You can detect which type is stored using boost::variant<>::which()
which returns an integer index of the binded variant type; so if you use blank as the first type, which() will return 0 when its blank
see the following example
typedef boost::variant< boost::blank , int , std::string > var_t;
var_t a;
assert( a.which() == 0 );
a = 18;
assert( a.which() == 1 );
hope this helps
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