如何确定boost :: variant变量是否为空?

时间:2015-07-09 14:43:58

标签: c++ boost variant

我已经定义了一个boost :: variant var,如下所示:

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

此变量在实例化但未初始化时具有类型boost::blank的值,因为boost::blank是传递给模板化boost :: variant的第一个类型。

在某些时候,我想知道foo是否已初始化。我试过这个,但效果不好:

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

我认为值得注意的是,当foo被初始化时(例如,foo = true),它可以被重置&#34;通过foo = boost::blank();

如何检查foo是否已初始化,即它的类型与boost::blank不同?

2 个答案:

答案 0 :(得分:9)

您可以定义访问者以检测“空白”:

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; }
};

像这样使用它:

bool is_blank(my_variant const& v) {
   return boost::apply_visitor(is_blank_f(), v);
}

答案 1 :(得分:6)

当第一种类型为&#34;有效&#34;,foo.which() == 0时。使用它。

  

返回:包含类型*this的有界类型集的从零开始的索引。 (例如,如果在包含variant<int, std::string>的{​​{1}}对象上调用,std::string将返回which()。)

http://www.boost.org/doc/libs/1_58_0/doc/html/boost/variant.html#idp288369344-bb