命名空间
变体
操作

std::optional<T>::value_or

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
template< class U = std::remove_cv_t<T> >
constexpr T value_or( U&& default_value ) const&;
(1) (C++17 起)
template< class U = std::remove_cv_t<T> >
constexpr T value_or( U&& default_value ) &&;
(2) (C++17 起)

如果 *this 包含值,则返回所包含的值,否则返回 default_value

1) 如果 std::is_copy_constructible_v<T> && std::is_convertible_v<U&&, T>false,则程序格式错误。
2) 如果 std::is_move_constructible_v<T> && std::is_convertible_v<U&&, T>false,则程序格式错误。

目录

[编辑] 参数

default_value - 如果 *this 不包含值,则返回的值。

[编辑] 返回值

1) has_value() ? **this : static_cast<T>(std::forward<U>(default_value));
2) has_value() ? std::move(**this) : static_cast<T>(std::forward<U>(default_value))

[编辑] 示例

#include <cstdlib>
#include <iostream>
#include <optional>
 
std::optional<const char*> maybe_getenv(const char* n)
{
    if (const char* x = std::getenv(n))
        return x;
    else
        return {};
}
 
int main()
{
    std::cout << maybe_getenv("SHELL").value_or("(none)") << '\n';
    std::cout << maybe_getenv("MYPWD").value_or("(none)") << '\n';
}

可能的输出

/usr/bin/zsh
(none)

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 3886 C++17 U 没有默认模板参数 已指定

[编辑] 参阅

返回所包含的值
(public member function) [编辑]