名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 工具庫‎ | expected
 
 
 
 
主模板
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()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) [編輯]