template<class U> constexpr T value_or(U&& v) const &; // (1)
template<class U> constexpr T value_or(U&& v) &&; // (2)
概要
正常値もしくは指定された値を取得する。
適格要件
- (1) :
is_copy_constructible_v<T> == true && is_convertible_v<U, T> == true
- (2) :
is_move_constructible_v<T> == true && is_convertible_v<U, T> == true
戻り値
- (1) :
has_value() ? **this : static_cast<T>(std::forward<U>(v))
- (2) :
has_value() ? std::move(**this) : static_cast<T>(std::forward<U>(v))
例
#include <expected>
#include <iostream>
#include <string>
int main()
{
std::expected<int, std::string> x = 42;
std::cout << x.value_or(0) << std::endl;
std::expected<int, std::string> y = std::unexpected{"ERR"};
std::cout << y.value_or(0) << std::endl;
}
出力
42
0
バージョン
言語
- C++23
処理系
- Clang: 16.0 ✅
- GCC: 12.1 ✅
- ICC: ??
- Visual C++: ??