阅读量:155
C++ 标准库没有直接提供类似于 Python 中 Option 或 Rust 中 Option 的实现
- 使用智能指针:可以使用 C++ 标准库中的智能指针,如
std::unique_ptr或std::shared_ptr。当指针为空时,可以将其视为 “None”,而非空时则表示存在一个值。
#include
#include
int main() {
std::unique_ptr<int> optionalInt;
if (optionalInt) {
std::cout << "Value: " << *optionalInt<< std class="hljs-keyword">else {
std::cout << "No value"<< std class="hljs-keyword">return 0;
}
- 使用
std::optional(C++17 引入):std::optional是一个可以包含值也可以不包含值的模板类。它可以用来表示一个值可能存在,也可能不存在的情况。
#include
#include
int main() {
std::optional<int> optionalInt;
if (optionalInt.has_value()) {
std::cout << "Value: "<< optionalInt class="hljs-built_in">value()<< std class="hljs-keyword">else {
std::cout << "No value"<< std class="hljs-keyword">return 0;
}
- 使用
std::variant(C++17 引入):std::variant是一个联合类型,可以存储其定义的类型集合中的一个类型的值。可以用它来表示一个值可能是多种类型之一,包括 “无值”(例如std::monostate)。
#include
#include
int main() {
std::variantint> optionalInt;
if (std::holds_alternative<int>(optionalInt)) {
std::cout << "Value: "<< std class="hljs-built_in">get<int>(optionalInt)<< std class="hljs-keyword">else {
std::cout << "No value"<< std class="hljs-keyword">return 0;
}
这些方法都可以用来表示一个值可能存在,也可能不存在的情况,从而类似于其他语言中的 Option 类型。选择哪种方法取决于你的具体需求和偏好。在 C++17 及更高版本中,std::optional 通常是最简单且最直接的选择。