3 ms·
I agree, the lack of pattern matching is a bummer. You should retry std::variant with the lambda overload trick though. It's kind of okay in terms of syntax.
by Galanwe 3y ago
I agree, the lack of pattern matching is a bummer. You should retry std::variant with the lambda overload trick though. It's kind of okay in terms of syntax.
using MyDiscreminatedUnion = std::variant<MyType1, MyType2, MyType3>;
MyDiscreminatedUnion var = MyType2{};
std::visit(overload {
[](MyType1 t1) {...},
[](MyType2 t2) {...},
[](auto t) {...},
}, var);
- coffeeaddict1 3y agoYou can even do better with something like: namespace StlHelpers { template<class... Ts> struct overload : Ts... { using Ts::operator()...; }; template<class... Ts> overload(Ts...) -> overload<Ts...>; template<class var_t, class... Func> auto visit(var_t & variant, Func &&... funcs) { return std::visit(overload{ funcs... }, variant); } } And then StlHelpers::visit(var, [](MyType1 t1) {...}, [](MyType2 t2) {...}, [](auto t) {...} );