std::holds_alternative(3)

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

std::holds_alternative(3) πŸ’…

okay so bestie, this page is from the C++ Standard Libary manual, and it’s all about checking whether a std::variant is currently holding one specific alternative. It’s giving type-safe vibe check, fr fr. ✨

✨ NAME ✨

  • std::holds_alternative β€” std::holds_alternative (that’s the name, no cap)

πŸ¦‹ Synopsis πŸ¦‹

Defined in header <variant>, and it’s been iconic since C++17:

Defined in header <variant>
template< class T, class... Types >
constexpr bool holds_alternative( const std::variant<Types...>& v )
(since C++17)
noexcept;

Checks if the variant v holds the alternative T.

The call is ill-formed if T does not appear exactly once in Types.... Exactly once, periodt. πŸ’€

πŸ’– Parameters πŸ’–

  • v β€” the variant to examine. She’s the main character here. πŸŽ€

✨ Return value ✨

true if the variant currently holds the alternative T, false otherwise. Slay. πŸ’…

πŸ’… Example πŸ’…

Run this code, bestie:

// Run this code

#include <variant>
#include <string>
#include <iostream>
int main()
{
    std::variant<int, std::string> v = "abc";
    std::cout << std::boolalpha
              << "variant holds int? "
              << std::holds_alternative<int>(v) << '\n'
              << "variant holds string? "
              << std::holds_alternative<std::string>(v) << '\n';
}

Output:

variant holds int? false
variant holds string? true

πŸ‘‘ See also πŸ‘‘

  • index β€” returns the zero-based index of the alternative held by the variant (public member function)
  • get(std::variant) (C++17) β€” reads the value of the variant given the index or the type (if the type is unique), throws on error (function template)

mwah πŸ’‹ source/version/date: http://cppreference.com, 2024.06.10, std::holds_alternative(3). 🫢

πŸ“¦ where this page comes from