如何判断一个boost::variant变量是否为空?
How to determine if a boost::variant variable is empty?
我定义了一个 boost::variant 变量,如下所示:
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
)时,可以通过 foo = boost::blank();
.
如何检查 foo
是否已初始化,即它的类型是否与 boost::blank
不同?
当第一个类型为"active"、foo.which() == 0
时。用那个。
Returns: The zero-based index into the set of bounded types of the contained type of *this
. (For instance, if called on a variant<int, std::string>
object containing a std::string
, which()
would return 1
.)
(http://www.boost.org/doc/libs/1_58_0/doc/html/boost/variant.html#idp288369344-bb)
您可以定义一个访问者来检测 '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; }
};
像这样使用它:
bool is_blank(my_variant const& v) {
return boost::apply_visitor(is_blank_f(), v);
}
我定义了一个 boost::variant 变量,如下所示:
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
)时,可以通过 foo = boost::blank();
.
如何检查 foo
是否已初始化,即它的类型是否与 boost::blank
不同?
当第一个类型为"active"、foo.which() == 0
时。用那个。
Returns: The zero-based index into the set of bounded types of the contained type of
*this
. (For instance, if called on avariant<int, std::string>
object containing astd::string
,which()
would return1
.)
(http://www.boost.org/doc/libs/1_58_0/doc/html/boost/variant.html#idp288369344-bb)
您可以定义一个访问者来检测 '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; }
};
像这样使用它:
bool is_blank(my_variant const& v) {
return boost::apply_visitor(is_blank_f(), v);
}