我已经定义了一个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
不同?
答案 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)