namespace std {
template<class E>
class unexpected;
}
概要
unexpectedクラスは、std::expected<T, E>に格納される任意の型Eのエラー値を表現するヘルパークラスである。
適格要件
型Eは非オブジェクト型、配列型、unexpectedの特殊化、CV修飾された型のいずれでもないこと。
メンバ関数
構築・破棄
| 名前 | 説明 | 対応バージョン |
|---|---|---|
(constructor) |
コンストラクタ | C++23 |
(destructor) |
デストラクタ | C++23 |
代入
| 名前 | 説明 | 対応バージョン |
|---|---|---|
constexpr unexpected& operator=(const unexpected&) = default; |
コピー代入演算子 | C++23 |
constexpr unexpected& operator=(unexpected&&) = default; |
ムーブ代入演算子 | C++23 |
swap |
他のunexpectedオブジェクトとデータを入れ替える |
C++23 |
値の観測
| 名前 | 説明 | 対応バージョン |
|---|---|---|
error |
エラー値を取得する | C++23 |
比較
| 名前 | 説明 | 対応バージョン |
|---|---|---|
operator== |
等値比較 | C++23 |
operator!= |
非等値比較 | C++23 |
非メンバ関数
| 名前 | 説明 | 対応バージョン |
|---|---|---|
swap |
2つのunexpectedオブジェクトを入れ替える |
C++23 |
推論補助
| 名前 | 説明 | 対応バージョン |
|---|---|---|
(deduction_guide) |
クラステンプレートの推論補助 | C++23 |
例
#include <expected>
#include <iomanip>
#include <iostream>
#include <string>
// 整数除算
std::expected<int, std::string> idiv(int a, int b)
{
if (b == 0) {
return std::unexpected{"divide by zero"};
}
if (a % b != 0) {
return std::unexpected{"out of domain"};
}
return a / b;
}
void dump_result(const std::expected<int, std::string>& v)
{
if (v) {
std::cout << *v << std::endl;
} else {
std::cout << std::quoted(v.error()) << std::endl;
}
}
int main()
{
dump_result(idiv(10, 2));
dump_result(idiv(10, 3));
dump_result(idiv(10, 0));
}
出力
5
"out of domain"
"divide by zero"
バージョン
言語
- C++23
処理系
- Clang: 16.0 ✅
- GCC: 12.1 ✅
- ICC: ??
- Visual C++: ??