- expected[meta header]
- class template[meta id-type]
- std[meta namespace]
- cpp23[meta cpp]
namespace std {
template<class E>
class unexpected;
}
unexpected
クラスは、任意の型E
の値をエラー値として表現する。
E
は非オブジェクト型、配列型、unexpected<U>
、CV修飾された型のいずれでもないこと。
名前 |
説明 |
対応バージョン |
operator= |
代入演算子 |
C++23 |
swap |
他のunexpected オブジェクトとデータを入れ替える |
C++23 |
名前 |
説明 |
対応バージョン |
error |
エラー値を取得する |
C++23 |
名前 |
説明 |
対応バージョン |
swap |
他の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]
5
"out of domain"
"divide by zero"