CppDS.com

C++ 98 11 14 17 20 手册

std::optional<T>::value_or

来自cppreference.com
< cpp‎ | utility‎ | optional
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等字符串转换
(C++17)
(C++17)
 
 
template< class U >
constexpr T value_or( U&& default_value ) const&;
(1) (C++17 起)
template< class U >
constexpr T value_or( U&& default_value ) &&;
(2) (C++17 起)

*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))

参数

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

返回值

*this 拥有值则为其当前值,否则为 default_value

异常

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

示例

#include <optional>
#include <iostream>
#include <cstdlib>
 
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("MYPWD").value_or("(none)") << '\n';
}

可能的输出:

(none)

参阅

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