◐ Shell
clean mode source ↗

std::experimental::optional<T>::value_or - cppreference.com

来自cppreference.com

template< class U > 
constexpr T value_or( U&& default_value ) const&;
(库基础 TS)
template< class U > 
constexpr T value_or( U&& default_value ) &&;
(库基础 TS)

如果 *this 具有值则返回其所含值,否则返回 default_value

1) 等价于 bool(*this) ? **this : static_cast<T>(std::forward<U>(default_value))

2) 等价于 bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(default_value))

Parameters

default_value - *this 为空的情况下使用的值
类型要求
- 为使用重载 (1), T 必须满足可复制构造 (CopyConstructible)
- 为使用重载 (2), T 必须满足可移动构造 (MoveConstructible)
-U&& 必须可转换为 T

返回值

如果 *this 含有值则为其所含值,否则为 default_value

异常

由返回值 T 所选中构造函数所抛出的任何异常。

示例

#include <cstdlib>
#include <experimental/optional>
#include <iostream>

std::experimental::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("MYPWD").value_or("(none)") << '\n';
}

可能的输出:

参阅