std::option...::has_value(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

✨ 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 πŸ’–

  1. true if *this contains a value ⭐
  2. false if *this does 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