cppreference.com - std::optional 将 std::optional 标识为“自 C++17 以来”可用。GCC 中的 C++ 标准支持 - C++1z 语言特性 列出了 c++17 特性,但是我没有在列表中看到 std::optional。std::optional 在 G++ 的哪里有文档记录?
#include <string>
#include <iostream>
#include <optional>
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b) {
if(b)
return "Godzilla";
else
return {};
}
int main()
{
std::cout << "create(false) returned "
<< create(false).value_or("empty") << '\n';
// optional-returning factory functions are usable as conditions of while and if
if(auto str = create(true)) {
std::cout << "create(true) returned " << *str << '\n';
}
}