std::variant::index(3)

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

std::variant::index πŸ’…

okay bestie, welcome to the std::variant::index(3) page from the C++ Standard Libary manual. We're checking which alternative a variant is currently holding, and honestly? iconic. 🫢


🌸 NAME 🌸

std::variant::index β€” std::variant::index. yes bestie, the name is the name, and it ate. πŸ’…

✨ Synopsis ✨

constexpr std::size_t index() const noexcept;  (since C++17)

okay so this is the signature, and it's constexpr std::size_t, const, and noexcept. It's been serving since C++17, no cap. ✨

Returns the zero-based index of the alternative that is currently held by the variant.

If the variant is valueless_by_exception, it returns variant_npos. so if your variant is in its empty era, you get variant_npos, and that's the vibe check. πŸ’€

πŸŽ€ Example πŸŽ€

// Run this code

#include <variant>
#include <string>
#include <iostream>
int main()
{
    std::variant<int, std::string> v = "abc";

    std::cout << "v.index = " << v.index() << '\n';

    v = {};

    std::cout << "v.index = " << v.index() << '\n';
}

this is literally "check the index, reset, check it again." main character behavior. 🌈

πŸ’– Output πŸ’–

v.index = 1
v.index = 0

so the first print is 1, then after v = {}; it's 0. slay. ✨

🌈 See also 🌈

  • holds_alternative β€” checks if a variant currently holds a given type. (C++17) (function template)
  • get(std::variant) β€” reads the value of the variant given the index or the type (if the type is unique), throws on error. (C++17) (function template)

sourced from http://cppreference.com, dated 2024.06.10, for std::variant::index(3) β€” mwah, bye bestie πŸ’…πŸ’–

πŸ“¦ where this page comes from