[英]How to use boost::blank
I want to add empty values to int
and double
with the help of boost::blank
.我想在
boost::blank
的帮助下向int
和double
添加空值。 Later, I want to check if these values are empty.后来,我想检查这些值是否为空。 I have had a hard time finding information on the functionality of
boost::blank
.我很难找到有关
boost::blank
功能的信息。 Can someone help with some examples of how to use boost::blank
?有人可以提供一些有关如何使用
boost::blank
示例吗?
boost::blank
is not quite what you're looking for.boost::blank
并不是你想要的。
Here's what boost::blank
is:这是
boost::blank
内容:
struct blank
{
};
// overloaded operators
// ...
It could be useful if you were creating a std::variant
(or boost::variant
) and wanted an "empty variant" like so:如果您正在创建
std::variant
(或boost::variant
)并想要一个“空变体”,这可能很有用:
std::variant<boost::blank, int, double, char> my_variant;
If you want to add an "empty" value for simply an int
or a double
in isolation, you should use std::optional<int>
( std::optional<double>
)如果要单独为
int
或double
添加“空”值,则应使用std::optional<int>
( std::optional<double>
)
You can check for empty values with a std::optional
like so:您可以使用
std::optional
检查空值,如下所示:
std::optional<int> value;
std::cout << std::boolalpha << value.has_value() << std::endl; // "false"
It's also implicitly convertible to bool
, so you can check for a value in an if
like so:它也可以隐式转换为
bool
,因此您可以像这样检查if
的值:
if (value)
std::cout << "Has a value: " << *value << std::endl; // branch not taken
And finally, you can ask to use a default if there's no value, like so:最后,如果没有值,您可以要求使用默认值,如下所示:
std::cout << value.value_or(0) << std::endl; // "0"
If boost::blank
is really what you're looking for, let's revisit the std::variant<blank, int, double>
scenario.如果
boost::blank
确实是您要找的,让我们重新审视std::variant<blank, int, double>
场景。
Construct an "empty" variant:构造一个“空”变体:
std::variant<boost::blank, int, double> my_variant;
or equivalently,或等效地,
std::variant<blank, int, double> my_variant = boost::blank{};
Next, define visitors for each type:接下来,为每种类型定义访问者:
struct my_visitor
{
void operator()(boost::blank) const
{
std::cout << "Variant is empty\n";
}
void operator()(int i) const
{
std::cout << "Variant has int with value " << i << std::endl;
}
void operator()(double d) const
{
std::cout << "Variant has double with value " << d << std::endl;
}
};
And we can execute the appropriate function using std::visit
:我们可以使用
std::visit
执行适当的函数:
// int
my_variant = 42;
std::visit(visitor, my_variant);
// double
my_variant = 1337.0;
std::visit(visitor, my_variant);
// reset to empty
my_variant = boost::blank{};
std::visit(visitor, my_variant);
You can also check for an "empty" variant
by calling holds_alternative
:您还可以通过调用
holds_alternative
来检查“空” variant
:
if (std::holds_alternative<blank>(my_variant))
std::cout << "Variant is empty\n";
variant
variant
演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.