0 Tage Serie
cpp / intermediate
Snippet

Typsichere Variant-Auswahl

std::variant bietet eine typsichere Alternative zu Unions. In Kombination mit std::visit ermöglicht es eine Verzweigungslogik, die den spezifischen aktuell gespeicherten Typ berücksichtigt.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <variant>
#include <string>
int main() {
std::variant<int, std::string> data = "C++ Standard";
// std::visit handles the control flow based on the active type
std::visit([](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, int>) {
std::cout << "Integer: " << arg << std::endl;
} else if constexpr (std::is_same_v<T, std::string>) {
std::cout << "String: " << arg << std::endl;
}
}, data);
return 0;
}
Erklärung
1
std::variant<int, std::string> data = ...
Deklariert eine Variable, die sicher entweder eine Ganzzahl oder einen String enthalten kann.
2
if constexpr (std::is_same_v<T, int>)
Eine bedingte Prüfung zur Kompilierzeit, um den Typ des Arguments des Visitors zu bestimmen.