Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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);



You 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) {...}
);




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: