也许你想要std::nullopt,它表示 optional 不具有价值,换句话说 optional + nullopt 正是 null 在其他语言中的含义。换句话说,std::optional + std::nullopt 将 null 的自然意义引入 C++,与其他语言相同。
通过std::nullopt,您可以控制函数中的可选参数,就像我在下面对add() 函数所做的那样。
您只需检查if (optional_value) 以了解它是否具有价值,这与if (optional_value.has_value()) 相同。见doc here。
您也可以使用.value_or(default) 来返回值或默认值,这与Python 中的var or default 或var if var is not None else default 用于None-able 参数相同。
你也可以通过*optional_value取消引用来获取可选的值,就像指针一样。 Doc here.
查看在实现add() 函数时使用可空选项的所有4 种可能性,它有4 种做同样事情的方式,选择更适合你的。
Try it online!
#include <optional>
#include <iostream>
int add(int x, std::optional<int> y = std::nullopt) {
return x + y.value_or(5);
// also possible to do same like this
return x + (y ? y.value() : 5);
// or same as
return x + (y ? *y : 5);
// or same as
if (y)
return x + *y;
else
return x + 5;
}
int main() {
std::cout << add(3) << std::endl;
std::cout << add(3, std::nullopt) << std::endl;
std::cout << add(3, 7) << std::endl;
}
输出:
8
8
10
换句话说,如果您希望任何变量同时保存某种类型的值和 null,那么只需将其包装到 std::optional 中,并使用 std::nullopt 来表示 null,如下例所示:
SomeClass obj; // non-nullable, can't be null
std::optional<SomeClass> obj2; // almost same as above but now is nullable
obj2 = obj; // you can naturally assign value of object
obj2 = std::nullopt; // this way you set variable to null
obj = *obj2; // this way you get value of object by using * dereference
obj = obj2.value(); // same as above instead of *
obj = obj2 ? *obj2 : default_value; // this way you check if obj2 is null, if not then get it's value through *, otherwise return default
obj = obj2.value_or(default_value); // same as last line above
if (obj2) DoSomething(); // checks if object is not null
if (obj2.has_value()) DoSomething(); // same as above
有关 std::optional 的信息,请参阅 all docs。