std::expected<T,E>::operator->, std::expected<T,E>::operator*
来自cppreference.com
| 主模板 |
||
| |
(1) | (C++23 起) |
| |
(2) | (C++23 起) |
| |
(3) | (C++23 起) |
| |
(4) | (C++23 起) |
| |
(5) | (C++23 起) |
| |
(6) | (C++23 起) |
void 部分特化 |
||
| |
(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注解
这些运算符不会检查 expected 是否表示预期值,用户可以使用 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; // UB, ex1 包含非预期值
assert(ex1.value_or(42) == 42);
std::expected<std::string, bool> ex2 = "Moon"s;
std::cout << "ex2:" << std::quoted(*ex2) << ",大小:" << ex2->size() << '\n';
// 你可以通过在 std::expected 的右值上调用 operator* 来“拿走”预期值
auto taken = *std::move(ex2);
std::cout << "拿走了 " << std::quoted(taken) << "\n"
"ex2:" << std::quoted(*ex2) << ",大小:" << ex2->size() << '\n';
}
可能的输出:
ex2:"Moon",大小:4
拿走了 "Moon"
ex2:"",大小:0
参阅
| 返回预期值 (公开成员函数) | |
| 如果有预期值则返回它,否则返回另一个值 (公开成员函数) | |
| 检查对象是否含有预期值 (公开成员函数) | |
| 返回非预期值 (公开成员函数) |