std::option...::has_value(3)
β¨ NAME β¨
std::optional::operatorbool,std::optional::has_value β okay so these two are literally the same vibe check but in different outfits π
(this whole page lives in the C++ Standard Libary manual, section 3, bestie π)
πΈ SYNOPSIS πΈ
constexpr explicit operator bool() const noexcept; (since C++17)
constexpr bool has_value() const noexcept; (since C++17)
Both of these are asking the exact same question: does *this actually contain a value or not? π
π¦ PARAMETERS π¦
- (none) β nope, nothing, zero, not a single parameter. she takes no args π«Ά
π RETURN VALUE π
trueif*thiscontains a value βfalseif*thisdoes not contain a value π
That's it. That's the whole function. iconically simple, no cap.
π EXAMPLE π
// Run this code
#include <optional>
#include <iostream>
int main()
{
std::cout << std::boolalpha;
std::optional<int> opt;
std::cout << opt.has_value() << '\n';
opt = 43;
if (opt)
std::cout << "value set to " << opt.value() << '\n';
else
std::cout << "value not set\n";
opt.reset();
if (opt.has_value())
std::cout << "value still set to " << opt.value() << '\n';
else
std::cout << "value no longer set\n";
}
β Output
false
value set to 43
value no longer set
so yeah, has_value() and operator bool are besties fr fr β one's a method, one's the explicit bool conversion, and both of them are just telling you whether the optional is holding something or is empty π§ noexcept and constexpr since C++17, periodt. π
mwah, kisses β this page came from http://cppreference.com, dated 2024.06.10 π bye bestie, go check your optionals π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms