std::variant_npos(3)

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

πŸ’– std::variant_npos(3) β€” C++ Standard Libary πŸ’–

okay bestie, welcome to the tiny-but-mighty page for std::variant_npos from the C++ Standard Libary β€” yes, that spelling is exactly what the header says πŸ’…

🌸 NAME 🌸

  • std::variant_npos β€” std::variant_npos - std::variant_npos β€” she's self-titled, no notes, periodt. πŸ’–

✨ Synopsis ✨

Defined in header <variant>:

inline constexpr std::size_t variant_npos = -1;  (since C++17)

This is a special value equal to the largest value representable by the type std::size_t, used as the return value of index() when valueless_by_exception() is true. That's the whole vibe check. πŸ¦‹


🧚 // Run this code 🧚

        #include <iostream>
        #include <stdexcept>
        #include <string>
        #include <variant>

        struct Demon
        {
            Demon(int) {}
            Demon(const Demon&) { throw std::domain_error("copy ctor"); }
            Demon& operator= (const Demon&) = default;
        };

        int main()
        {
            std::variant<int, Demon> var{42};
            std::cout
                << std::boolalpha
                << "index == npos: " << (var.index() == std::variant_npos) <<
       '\n';

            try { var = Demon{666}; } catch (const std::domain_error& ex)
            {
                std::cout
                    << "Exception: " << ex.what() << '\n'
                    << "index == npos: " << (var.index() == std::variant_npos)
       << '\n'
                    << "valueless: " << var.valueless_by_exception() << '\n';
            }
        }

🌸 Possible output: 🌸

        index == npos: false
        Exception: copy ctor
        index == npos: true
        valueless: true

🌈 See also 🌈

  • index β€” returns the zero-based index of the alternative held by the variant (public member function).
  • valueless_by_exception β€” checks if the variant is in the invalid state (public member function).

kiss kiss, bestie β€” this page came from http://cppreference.com, dated 2024.06.10, and it's literally std::variant_npos(3) πŸ’…βœ¨πŸ«Ά

πŸ“¦ where this page comes from