std::optional<T>::value
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Relational operators (deprecated in C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
Common vocabulary types
std::optional
optional::value
(C++26)
(C++26)
(C++23)
(C++23)
(C++23)
constexpr T& value() &;
constexpr const T& value() const &;
(1)
(since C++17)
constexpr const T& value() const &;
constexpr T&& value() &&;
constexpr const T&& value() const &&;
(2)
(since C++17)
constexpr const T&& value() const &&;
If *this contains a value, returns a reference to the contained value.
Otherwise, throws a std::bad_optional_access exception.
[edit] Parameters
(none)
[edit] Return value
A reference to the contained value.
[edit] Exceptions
std::bad_optional_access if *this does not contain a value.
[edit] Notes
The dereference operator operator*() does not check if this optional contains a value, which may be more efficient than value()
.
[edit] Example
Run this code
#include <iostream> #include <optional> int main() { std::optional <int> opt = {}; try { [[maybe_unused]] int n = opt.value(); } catch(const std::bad_optional_access & e) { std::cout << e.what() << '\n'; } try { opt.value() = 42; } catch(const std::bad_optional_access & e) { std::cout << e.what() << '\n'; } opt = 43; std::cout << *opt << '\n'; opt.value() = 44; std::cout << opt.value() << '\n'; }
Output:
bad optional access bad optional access 43 44
[edit] See also
(C++17)
(class) [edit]