Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check boost::variant<T> for null

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?

like image 491
Tony The Lion Avatar asked Mar 15 '11 13:03

Tony The Lion


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.

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.

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 any?

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.


1 Answers

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

like image 166
lurscher Avatar answered Oct 17 '22 07:10

lurscher