Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a boost::variant variable is empty?

Tags:

c++

boost

variant

I have defined a boost::variant var like this:

boost::variant<boost::blank, bool, int> foo;

This variable, when instantiated but not initialized, has a value of type boost::blank, because boost::blank is the first type passed to the templated boost::variant.

At some point, I want to know if foo has been initialized. I've tried this, but with no good results:

if (foo) //doesn't compile
if (foo != boost::blank()) //doesn't compile
if (!(foo == boost::blank())) //doesn't compile

I think it's worth noticing that, when foo has been initialized (eg., foo = true), it can be "reset" by doing foo = boost::blank();.

How can I check if foo has been initialized, ie, it has a different type than boost::blank?

like image 361
FerranMG Avatar asked Jul 09 '15 14:07

FerranMG


1 Answers

You could define a visitor to detect the 'blankness':

struct is_blank_f : boost::static_visitor<bool> {
   bool operator()(boost::blank) const { return true; }

   template<typename T>
   bool operator()(T const&) const { return false; }
};

Use it like so:

bool is_blank(my_variant const& v) {
   return boost::apply_visitor(is_blank_f(), v);
}
like image 170
sehe Avatar answered Sep 21 '22 18:09

sehe