std::get_if (std::variant)
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Relational operators (deprecated in C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
Common vocabulary types
std::variant
(C++26)
get_if
Defined in header
<variant>
(1)
(since C++17)
template< std::size_t I, class... Types >
constexpr std::add_pointer_t <std::variant_alternative_t <I, std::variant <Types...>>>
template< std::size_t I, class... Types >
constexpr std::add_pointer_t <const std::variant_alternative_t <I, std::variant <Types...>>>
(2)
(since C++17)
template< class T, class... Types >
constexpr std::add_pointer_t <T>
template< class T, class... Types >
constexpr std::add_pointer_t <const T>
1) Index-based non-throwing accessor: If pv is not a null pointer and pv->index() == I, returns a pointer to the value stored in the variant pointed to by pv. Otherwise, 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....[edit] Template parameters
I
-
index to look up
Type
-
unique type to look up
[edit] Parameters
pv
-
pointer to a variant
[edit] Return value
Pointer to the value stored in the pointed-to variant or null pointer on error.
[edit] Example
Run this code
#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!
[edit] See also
(C++17)
(function template) [edit]