3 ms·
If `match` compiles down to a switch case on the type discriminator then it can easily beat current implentations of C++'s std::visit on std::variant. I assume
by steerablesafe 6y ago
If `match` compiles down to a switch case on the type discriminator then it can easily beat current implentations of C++'s std::visit on std::variant.
I assume pattern matching must be exhaustive. Can there be a default case?
- Hirrolot 6y agoYes, just write otherwise { ... } to handle a default case.
- sesuximo 6y agoWhat else can std visit generate? I’d imagine it does exactly that
- ynik 6y agostd::variant is implemented with variadic templates; but C++ doesn't have a "variadic switch" statement. So std::visit cannot directly use a switch statement. Instead it's usually implemented as a recursive function with the hope that the compiler will unroll the recursion and optimize it into a switch. This hope usually doesn't work out in practice.
- steerablesafe 6y agoAFAIK the usual implementation is statically generating an array of function pointers and dispatching based on the type discriminator. This works even less for inlining.
- sesuximo 6y agoOn my phone so cannot check, but I thought this was mostly a solved problem? Inlining/folding a jump table should be easy enough especially since the table can be const
- steerablesafe 6y agohttps://godbolt.org/z/d4838K https://godbolt.org/z/d4838K Doesn't happen, apparently. edit: For a short while libc++ adopted mpark's variant visit, which AFAIK compiles down to switch case with some hand coding. AFAIK it had other problems so they rolled back to the constexpr array of function pointers. https://github.com/mpark/variant https://github.com/mpark/variant
- sesuximo 6y agoIf you call foo with an int or with a double, then it gets inlined. I don’t think they can inline foo as you’ve written it because the variant could be valueless by exception.
- sesuximo 6y agoI just looked into this a bit more. For the simple examples I tried, clang and gcc inline + const prop calls to std::visit with O2.