std::expected<T,E>::value_or
来自cppreference.com
| 主模板 |
||
| |
(1) | (C++23 起) |
| |
(2) | (C++23 起) |
在 *this 包含预期值时返回它,否则返回 default_value。
void 部分特化没有这些成员函数。
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))示例
可在 Compiler Explorer 上尝试。
运行此代码
#include <cstdlib>
#include <expected>
#include <print>
#include <system_error>
#include <utility>
std::expected<const char*, std::errc> try_getenv(const char* name)
{
if (const char* env{std::getenv(name)})
return env;
return std::unexpected{std::errc::function_not_supported};
}
int main()
{
for (auto env : {"SHELL", "OS"})
std::println("{}: {}", env, try_getenv(env).value_or("(unknown)"));
}
可能的输出:
SHELL: /usr/bin/bash
OS: (unknown)
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3886 | C++23 | U 没有默认模板实参
|
已指定 |
参阅
| 返回预期值 (公开成员函数) |