Fer*_*nMG 10 c++ boost variant
我已经定义了一个boost :: variant var,如下所示:
boost::variant<boost::blank, bool, int> foo;
Run Code Online (Sandbox Code Playgroud)
该变量在实例化但未初始化时具有type值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
Run Code Online (Sandbox Code Playgroud)
我认为值得注意的是,当foo初始化(例如,foo = true)时,它可以通过执行来"重置" foo = boost::blank();.
如何检查是否foo已初始化,即它的类型不同boost::blank?
seh*_*ehe 11
您可以定义访问者以检测"空白":
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; }
};
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
bool is_blank(my_variant const& v) {
return boost::apply_visitor(is_blank_f(), v);
}
Run Code Online (Sandbox Code Playgroud)
当第一种类型是"活跃的"时,foo.which() == 0.用那个.
返回:从包含类型的有界类型集合中从零开始的索引
*this.(例如,如果在variant<int, std::string>包含a 的对象上调用std::string,which()则会返回1.)
(http://www.boost.org/doc/libs/1_58_0/doc/html/boost/variant.html#idp288369344-bb)