名前空間
変種
操作

std::expected<T,E>::operator->, std::expected<T,E>::operator*

From cppreference.com
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
プライマリテンプレート
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) 何も返しません。

If has_value() is false, the behavior is undefined。(has_value()がfalseの場合、動作は未定義です。)

目次

[編集] 戻り値

3,4) val
5,6) std::move(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; // error, ex1 contains an expected value of type int
    ex1 = std::unexpected("error"s);
    // *ex1 = 13; // UB, ex1 contains an unexpected value
    assert(ex1.value_or(42) == 42);
 
    std::expected<std::string, bool> ex2 = "Moon"s;
    std::cout << "ex2: " << std::quoted(*ex2) << ", size: " << ex2->size() << '\n';
 
    // You can "take" the expected value by calling operator* on an std::expected rvalue
 
    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

[編集] 関連項目

期待される値を返す
(public member function) [編集]
期待される値が存在すればそれを返し、そうでなければ別の値を返す
(public member function) [編集]
オブジェクトが期待される値を保持しているか確認する
(public member function) [編集]
期待されない値を返す
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)