命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | utility‎ | expected
 
 
 
 
主模板
constexpr const T* operator->() const noexcept;
(1) (since C++23)
constexpr T* operator->() noexcept;
(2) (since C++23)
constexpr const T& operator*() const& noexcept;
(3) (since C++23)
constexpr T& operator*() & noexcept;
(4) (since C++23)
constexpr const T&& operator*() const&& noexcept;
(5) (since C++23)
constexpr T&& operator*() && noexcept;
(6) (since C++23)
void 部分特化
constexpr void operator*() const noexcept;
(7) (since 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

[编辑] 参见

返回期望值
(公共成员函数) [编辑]
如果存在则返回期望值,否则返回另一个值
(公共成员函数) [编辑]
检查对象是否包含期望值
(公共成员函数) [编辑]
返回非期望值
(公共成员函数) [编辑]