std::get_if
From cppreference.com
| Defined in header <variant>
|
||
| (1) | (since C++17) | |
| template <std::size_t I, class... Types> constexpr std::add_pointer_t< |
||
| template <std::size_t I, class... Types> constexpr std::add_pointer_t< |
||
| (2) | (since C++17) | |
| template <class T, class... Types> constexpr std::add_pointer_t<T> get_if(variant<Types...>* pv) |
||
| template <class T, class... Types> constexpr std::add_pointer_t<const T> get_if(const variant<Types...>* pv) |
||
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 or if T_I is a (possibly cv-qualified) type void.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... or if T_I is a (possibly cv-qualified) type void.Contents |
[edit] Parameters
| I | - | index to look up |
| Type | - | unique type to look up |
| pv | - | pointer to a variant |
[edit] Return value
Pointer to the value stored in the pointed-to variant or null pointer on error.
[edit] Exceptions
1,2)
noexcept specification:
noexcept
[edit] Example
Run this code
#include <variant> #include <iostream> int main() { std::variant<int, float> v{12}; if(auto pval = std::get_if<int>(&v)) std::cout << "variant value: " << *pval << '\n'; else std::cout << "failed to get value!" << '\n'; }
Output:
variant value: 12
[edit] See also
| (C++17) |
reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) |