std:: get (std::variant)
|
Definiert im Header
<variant>
|
||
| (1) | (seit C++17) | |
|
template
<
std::
size_t
I,
class
...
Types
>
constexpr
std::
variant_alternative_t
<
I,
std::
variant
<
Types...
>>
&
|
||
|
template
<
std::
size_t
I,
class
...
Types
>
constexpr
std::
variant_alternative_t
<
I,
std::
variant
<
Types...
>>
&&
|
||
|
template
<
std::
size_t
I,
class
...
Types
>
constexpr
const
std::
variant_alternative_t
<
I,
std::
variant
<
Types...
>>
&
|
||
|
template
<
std::
size_t
I,
class
...
Types
>
constexpr
const
std::
variant_alternative_t
<
I,
std::
variant
<
Types...
>>
&&
|
||
| (2) | (seit C++17) | |
|
template
<
class
T,
class
...
Types
>
constexpr T & get ( std:: variant < Types... > & v ) ; |
||
|
template
<
class
T,
class
...
Types
>
constexpr T && get ( std:: variant < Types... > && v ) ; |
||
|
template
<
class
T,
class
...
Types
>
constexpr const T & get ( const std:: variant < Types... > & v ) ; |
||
|
template
<
class
T,
class
...
Types
>
constexpr const T && get ( const std:: variant < Types... > && v ) ; |
||
I
kein gültiger Index im Variant ist.
T
enthält, gibt eine Referenz auf den in
v
gespeicherten Wert zurück. Andernfalls wird
std::bad_variant_access
geworfen. Der Aufruf ist ill-formed, wenn
T
kein eindeutiges Element von
Types...
ist.
Inhaltsverzeichnis |
Template-Parameter
| I | - | Index für die Suche |
| T | - | Eindeutiger Typ für die Suche |
| Types... | - |
Typen, die das
variant
bilden
|
Parameter
| v | - |
a
variant
|
Rückgabewert
Referenz auf den im Variant gespeicherten Wert.
Exceptions
Beispiel
#include <iostream> #include <string> #include <variant> int main() { std::variant<int, float> v{12}, w; std::cout << std::get<int>(v) << '\n'; w = std::get<int>(v); w = std::get<0>(v); // gleiche Wirkung wie die vorherige Zeile // std::get<double>(v); // Fehler: kein double in [int, float] // std::get<3>(v); // Fehler: gültige Indexwerte sind 0 und 1 try { w = 42.0f; std::cout << std::get<float>(w) << '\n'; // ok, gibt 42 aus w = 42; std::cout << std::get<float>(w) << '\n'; // wirft Exception } catch (std::bad_variant_access const& ex) { std::cout << ex.what() << ": w enthielt int, nicht float\n"; } }
Mögliche Ausgabe:
12 42 Unexpected index: w contained int, not float
Siehe auch
|
(C++17)
|
erhält einen Zeiger auf den Wert eines gezeigten
variant
gegeben des Index oder des Typs (falls eindeutig), gibt null bei Fehler zurück
(Funktions-Template) |
|
(C++11)
|
greift auf bestimmtes Element eines Tupels zu
(Funktions-Template) |
|
(C++11)
|
greift auf ein Element eines
array
zu
(Funktions-Template) |
|
(C++11)
|
greift auf ein Element eines
pair
zu
(Funktions-Template) |
|
(C++20)
|
erhält Iterator oder Sentinel aus einem
std::ranges::subrange
(Funktions-Template) |
|
(C++26)
|
erhält eine Referenz auf Real- oder Imaginärteil aus einem
std::complex
(Funktions-Template) |