std::expected<T,E>:: operator bool, std::expected<T,E>:: has_value
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::expected
| Member functions | ||||
| Observers | ||||
|
expected::operator bool
expected::has_value
|
||||
| Monadic operations | ||||
| Modifiers | ||||
| Non-member functions | ||||
| Helper classes | ||||
|
constexpr
explicit
operator
bool
(
)
const
noexcept
;
|
(1) | (自 C++23 起) |
|
constexpr
bool
has_value
(
)
const
noexcept
;
|
(2) | (自 C++23 起) |
检查 * this 是否表示期望值。
目录 |
返回值
注释
一个
std::expected
对象永远不会处于无值状态。若
has_value()
返回
true
,可通过
operator*()
访问期望值;否则可通过
error()
访问非期望值。
示例
运行此代码
#include <charconv> #include <concepts> #include <cstdint> #include <expected> #include <print> #include <string> #include <string_view> #include <system_error> template<std::integral Int = int> constexpr std::expected<Int, std::string> to_int(std::string_view str) { Int value{}; const auto [_, ec] = std::from_chars(str.data(), str.data() + str.size(), value); if (ec == std::errc()) return value; return std::unexpected{std::move(std::make_error_code(ec).message())}; } int main() { if (auto result = to_int("42"); result.has_value()) std::println("{}", *result); // 检查后可以安全使用 operator* else std::println("{}", result.error()); if (const auto result = to_int("not a number"); result) std::println("{}", *result); else std::println("{}", result.error()); if (const auto result{to_int<std::int16_t>("32768")}) // 隐式调用 (1) std::println("{}", *result); else std::println("{}", result.error()); }
可能的输出:
42 Invalid argument Numerical result out of range
参见
|
访问期望值
(公开成员函数) |
|
|
返回非期望值
(公开成员函数) |
|
|
检查对象是否包含值
(
std::optional<T>
的公开成员函数)
|