- expected[meta header]
- class template[meta id-type]
- std[meta namespace]
- cpp23[meta cpp]
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 |
名前 |
説明 |
対応バージョン |
swap |
2つのunexpected オブジェクトを入れ替える |
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));
}
- std::unexpected[color ff0000]
- std::expected[link expected.md]
- std::quoted[link ../iomanip/quoted.md]
5
"out of domain"
"divide by zero"