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>
の公開メンバ関数)
|