Created
November 24, 2023 02:31
-
-
Save 0xcafed00d/ef42c4e5d470fb963e420d93b9d1da84 to your computer and use it in GitHub Desktop.
fun with variants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <variant> | |
#include <string> | |
#include <iostream> | |
#include <array> | |
struct A { | |
int a = 5; | |
char b[100]; | |
}; | |
struct B { | |
float a = 0.1f; | |
char b[200]; | |
}; | |
struct C { | |
double a = 0.3; | |
char b[300]; | |
}; | |
using var_t = std::variant<A,B,C>; | |
auto printval = [](auto& S) { | |
std::cout << S.a << "\n"; | |
}; | |
auto set = [](auto& S) { | |
std::cout << sizeof(S) << "\n"; | |
S.a = {}; | |
}; | |
template <typename var_t, std::size_t I = 0> | |
void default_init_from_index (std::size_t index, var_t& v) | |
{ | |
if (index >= std::variant_size_v<var_t>){ | |
throw std::bad_variant_access(); | |
} | |
if constexpr (I < std::variant_size_v<var_t>) | |
{ | |
if (I == index){ | |
v = std::variant_alternative_t<I, var_t>{}; | |
return; | |
} | |
default_init_from_index<var_t, I + 1>(index, v); | |
} | |
} | |
int main () { | |
std::array<int, std::variant_size_v<var_t>> a; | |
auto x = std::variant_alternative_t<0, var_t>{}; | |
var_t y = B{}; | |
std::visit(printval, y); | |
var_t v; | |
for (size_t i = 0; i < std::variant_size_v<var_t>; i++){ | |
default_init_from_index(i, v); | |
std::visit(printval, v); | |
} | |
for (size_t i = 0; i < std::variant_size_v<var_t>; i++){ | |
default_init_from_index(i, v); | |
std::visit(set, v); | |
std::visit(printval, v); | |
} | |
try { | |
default_init_from_index(4, v); | |
} catch (std::bad_variant_access& e){ | |
std::cout<<e.what()<<"\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment