Namespaces
Variants

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

来自 zh.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() 为 false,则行为未定义。

(C++26 前)

若 has_value() 为 false:

(C++26 起)

返回值

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; // 错误: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

参见

返回期望值
(公开成员函数)
若存在则返回期望值,否则返回另一值
(公开成员函数)
检查对象是否包含期望值
(公开成员函数)
返回非期望值
(公开成员函数)