std::variant::index(3)
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
- 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