C++17 std::optional in G++?

5

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';
    }
}

8
"optional" 不是C++的语言特性,而是C++17的库特性。因此它不会列在语言特性部分中。 - Nicol Bolas
1个回答

12

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接