std::get_if(std::variant)(3)

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

πŸ’– std::get_if(std::variant) πŸ’–

std::get_if(std::variant)(3) β€” okay bestie, this is the C++ Standard Libary manual page for the variant-peeking function, and it's giving "look before you leap, no throwing" energy πŸ’…. Yes, "Libary" is exactly how it's spelled up there. We move.

🌸 NAME 🌸

std::get_if(std::variant) β€” std::get_if(std::variant)

✨ Synopsis ✨

Defined in header <variant>.

template< std::size_t I, class... Types >
constexpr std::add_pointer_t<std::variant_alternative_t<I, std::variant<Types...>>>
    get_if( std::variant<Types...>* pv ) noexcept;

template< std::size_t I, class... Types >
constexpr std::add_pointer_t<const std::variant_alternative_t<I, std::variant<Types...>>>
    get_if( const std::variant<Types...>* pv ) noexcept;

(1) (since C++17)

template< class T, class... Types >
constexpr std::add_pointer_t<T>
    get_if( std::variant<Types...>* pv ) noexcept;

template< class T, class... Types >
constexpr std::add_pointer_t<const T>
    get_if( const std::variant<Types...>* pv ) noexcept;

(2) (since C++17)

  1. Index-based non-throwing accessor: if pv is not a null pointer and pv->index() == I, it returns a pointer to the value stored in the variant pointed to by pv. Otherwise, it returns a null pointer value. The call is ill-formed if I is not a valid index in the variant.
  2. Type-based non-throwing accessor: equivalent to (1) with I being the zero-based index of T in Types.... The call is ill-formed if T is not a unique element of Types....

πŸŽ€ Parameters πŸŽ€

  • I β€” index to look up.
  • Type β€” unique type to look up.
  • pv β€” pointer to a variant.

πŸ¦‹ Return value πŸ¦‹

Pointer to the value stored in the pointed-to variant or null pointer on error. Periodt. ✨

🌈 Example 🌈

The page literally says // Run this code, so here's the code, copied exactly:

        #include <iostream>
        #include <variant>

        int main()
        {
            auto check_value = [](const std::variant<int, float>& v)
            {
                if (const int* pval = std::get_if<int>(&v))
                    std::cout << "variant value: " << *pval << '\n';
                else
                    std::cout << "failed to get value!" << '\n';
            };

            std::variant<int, float> v{12}, w{3.f};
            check_value(v);
            check_value(w);
        }

Output:

        variant value: 12
        failed to get value!

πŸ‘‘ See also πŸ‘‘

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

🏷️ Category 🏷️

  • Uses of dcl rev begin with nonempty note

Okay that's the whole page, bestie πŸ’– no cap. Footer folded into a cute sign-off: source/version http://cppreference.com, date 2024.06.10, manual page std::get_if(std::variant)(3) 🫢✨

πŸ“¦ where this page comes from