1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <iomanip> #include <iostream> #include <string> #include <type_traits> #include <variant> #include <vector>
using var_t = std::variant<int, long, double, std::string>;
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
int main() { std::vector<var_t> vec = {10, 15l, 1.5, "hello"}; for (auto& v : vec) { std::visit([](auto&& arg) {std::cout << arg; }, v);
var_t w = std::visit([](auto&& arg)->var_t {return arg + arg; }, v);
std::cout << ". After doubling, variant holds.";
std:visit([](auto&& arg) { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, int>) std::cout << "int with value " << arg << '\n'; else if constexpr (std::is_same_v<T, long>) std::cout << "long with value " << arg << '\n'; else if constexpr (std::is_same_v<T, double>) std::cout << "double with value " << arg << '\n'; else if constexpr (std::is_same_v<T, std::string>) std::cout << "std::string with value " << arg << '\n'; else static_assert(always_false_v<T>, "non-exhaustive visitor!"); }, w); }
for (auto& v : vec) { std::visit(overloaded{ [](auto arg) {std::cout << arg << ' '; }, [](double arg) {std::cout << std::fixed << arg << ' '; }, [](const std::string arg) {std::cout << std::quoted(arg) << ' '; }, }, v); }
system("pause"); }
|