Namespaces
Variants

std::optional<T>::value_or

从 zh.cppreference.net
 
 
 
 
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 does not have a default template argument specified

参见

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