check boost::variant<T> for null

Tony The Lion picture Tony The Lion · Mar 15, 2011 · Viewed 10k times · Source

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?

Answer

lurscher picture lurscher · Oct 6, 2011

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