std::optional<T>::value_or

来自cppreference.com
< 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 3886C++17U 没有默认模板实参已指定

参阅

返回所含值
(公开成员函数)