4 ms·
This works out really nicely when combined with variadic template tricks. (Taken from CPP Reference) // Helper for creating anonymous visitor functions tem
by TFortunato 6y ago
This works out really nicely when combined with variadic template tricks. (Taken from CPP Reference)
// Helper for creating anonymous visitor functions
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
using var_t = std::variant<int, long, double, std::string>;
std::vector<var_t> vec = {10, 15l, 1.5, "hello"};
// Type matching visitor
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);
}
Outputs: 10 15 1.500000 "hello"
- zeotroph 6y agoThat does not give you destructuring though, so to distinguish different variants of the same type you are left with a classic `if` inside the lambda. Also this has "language support" in the sense that it is (again) implemented via template meta programming, i.e. the compile time is impacted quite heavily. See "std::visit is everything wrong with modern C++": https://bitbashing.io/std-visit.html https://bitbashing.io/std-visit.html This standards proposal would add proper match (named, of course, inspect) support: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0095r1.html http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p009...
- TFortunato 6y agoYes, I'm definitely not saying that std::visit is perfect by any stretch of the imagination
- dunefox 6y agoWhat a ridiculous language C++ is.