std::nullopt_t(3)

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

✨ NAME ✨

std::nullopt_t β€” bestie, it's literally the icon of "no thanks, I'm good" for optionals πŸŽ€


✨ SYNOPSIS ✨

First things first, it's defined in the header <optional>:

struct nullopt_t;             (since C++17)

So std::nullopt_t is this empty little class type, and its whole personality is flagging when an optional is straight-up uninitialized, like a cute little "no value here, bestie πŸ’…" vibe.

The main character moment? std::optional has a constructor that takes nullopt_t as its single argument, and that constructor creates an optional that does not contain a value. Periodt. ✨

Now for the rules, and yes we love a strict queen:

std::nullopt_t must be a non-aggregate LiteralType, and it cannot have a default constructor or an initializer-list constructor. Not negotiable.

It must also have a constexpr constructor that takes some implementation-defined literal type. Yes, that's a thing, and yes it's giving very specific. 🌸


✨ NOTES ✨

Okay so why are the constructors so picky? The constraints on nullopt_t's constructors exist so that both op = {}; and op = nullopt; work as the syntax for disengaging an optional object. It's all for the vibes of a clean little reset. 🧚

A possible implementation of this class is:

struct nullopt_t {
    constexpr explicit nullopt_t(int) {}
};

That's it. That's the whole baddie. Simple, effective, highkey iconic. πŸ‘‘


✨ SEE ALSO ✨

  • nullopt β€” an object of type nullopt_t, and yes bestie it's a C++17 constant, so gaze upon it. 🌈

That's the whole page, babe! Source is http://cppreference.com, version date 2024.06.10, and this adorable little manual page is filed under std::nullopt_t(3). Now go forth and be optional. πŸ’–πŸ¦‹βœ¨

πŸ“¦ where this page comes from