std::expected<T,E>::operator->, std::expected<T,E>::operator*
ja.cppreference.net より
| プライマリテンプレート |
||
constexpr const T* operator->() const noexcept;
|
(1) | (C++23 以降) |
constexpr T* operator->() noexcept;
|
(2) | (C++23 以降) |
constexpr const T& operator*() const& noexcept;
|
(3) | (C++23 以降) |
constexpr T& operator*() & noexcept;
|
(4) | (C++23 以降) |
constexpr const T&& operator*() const&& noexcept;
|
(5) | (C++23 以降) |
constexpr T&& operator*() && noexcept;
|
(6) | (C++23 以降) |
void 部分特殊化 |
||
constexpr void operator*() const noexcept;
|
(7) | (C++23 以降) |
*this に含まれている期待値にアクセスします。
1,2) 期待値へのポインタを返します。
3-6) 期待値への参照を返します。
7) 何も返しません。
|
has_value() が |
(C++26 まで) |
|
has_value() が |
(C++26 以降) |
戻り値
1,2)
std::
addressof
(
val
)
3,4)
val
注記
これらの演算子はoptionalが期待される値を保持しているかどうかをチェックしません。ユーザーは手動で
has_value()
または
operator bool()
を使用して確認できます。あるいは、チェック付きアクセスが必要な場合は、
value()
または
value_or()
を使用できます。
例
このコードを実行
#include <cassert> #include <expected> #include <iomanip> #include <iostream> #include <string> int main() { using namespace std::string_literals; std::expected<int, std::string> ex1 = 6; assert(*ex1 == 6); *ex1 = 9; assert(*ex1 == 9); // *ex1 = "error"s; // エラー: ex1はint型の期待値を含む ex1 = std::unexpected("error"s); // *ex1 = 13; // 未定義動作: ex1は期待しない値を含む assert(ex1.value_or(42) == 42); std::expected<std::string, bool> ex2 = "Moon"s; std::cout << "ex2: " << std::quoted(*ex2) << ", size: " << ex2->size() << '\n'; // std::expectedの右辺値に対してoperator*を呼び出すことで期待値を「取得」できる auto taken = *std::move(ex2); std::cout << "taken " << std::quoted(taken) << "\n" "ex2: " << std::quoted(*ex2) << ", size: " << ex2->size() << '\n'; }
出力例:
ex2: "Moon", size: 4 taken "Moon" ex2: "", size: 0
関連項目
|
期待される値を返す
(公開メンバ関数) |
|
|
期待される値が存在する場合はそれを、それ以外の場合は別の値を返す
(公開メンバ関数) |
|
|
オブジェクトが期待される値を含むかどうかをチェックする
(公開メンバ関数) |
|
|
予期しない値を返す
(公開メンバ関数) |