命名空间
变体
操作

std::experimental::optional<T>::value_or

来自 cppreference.cn
 
 
实验性
技术规范
文件系统库 (filesystem TS)
库基础 (library fundamentals TS)
库基础 2 (library fundamentals TS v2)
库基础 3 (library fundamentals TS v3)
并行性扩展 (parallelism TS)
并行性扩展 2 (parallelism TS v2)
并发性扩展 (concurrency TS)
并发性扩展 2 (concurrency TS v2)
概念 (concepts TS)
范围 (ranges TS)
反射 (reflection TS)
数学特殊函数 (special functions TR)
实验性非TS
模式匹配
线性代数
std::execution
契约
2D图形
 
 
 
template< class U >
constexpr T value_or( U&& default_value ) const&;
(library fundamentals TS)
template< class U >
constexpr T value_or( U&& default_value ) &&;
(library fundamentals 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))

目录

[edit] 参数

default_value - *this 为空时使用的值
类型要求
-
T 必须满足 CopyConstructible 的要求才能使用重载 (1)。
-
T 必须满足 MoveConstructible 的要求才能使用重载 (2)。
-
U&& 必须可转换为 T

[edit] 返回值

如果 *this 包含值,则返回当前值,否则返回 default_value

[edit] 异常

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

[edit] 示例

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

可能的输出

(none)

[edit] 参见

返回包含的值
(公共成员函数) [edit]