std::get_if(std::variant)(3)
π 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)
- Index-based non-throwing accessor: if
pvis not a null pointer andpv->index() == I, it returns a pointer to the value stored in the variant pointed to bypv. Otherwise, it returns a null pointer value. The call is ill-formed ifIis not a valid index in the variant. - Type-based non-throwing accessor: equivalent to (1) with
Ibeing the zero-based index ofTinTypes.... The call is ill-formed ifTis not a unique element ofTypes....
π 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
- 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