Skip to content

Instantly share code, notes, and snippets.

@lakinwecker
Created February 11, 2020 23:03
Show Gist options
  • Save lakinwecker/c4ac5ed62b6e190172134c5461a1d10c to your computer and use it in GitHub Desktop.
Save lakinwecker/c4ac5ed62b6e190172134c5461a1d10c to your computer and use it in GitHub Desktop.
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
// the variant to visit
using var_t = std::variant<int, long, double, std::string>;
// helper type for the visitor #4
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main() {
std::vector<var_t> vec = {10, 15l, 1.5, "hello"};
for (auto& v: vec) {
// 4. another type-matching visitor: a class with 3 overloaded operator()'s
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment