Several years back I found an interesting question on Reddit. Essentially the author asks why there is no way to expand a pack into a sequence of case labels followed by a statement. It was illustrated with the following imaginary syntax:1 2 3 4 5 6 7 8 9 10 11 template <class Visitor, class Variant, std::size_t ... Is> auto visit_impl(Visitor visitor, Variant && variant, std::index_sequence<Is...>) { auto i = variant.index(); switch (i) { (case Is: return visitor(get<Is>(variant));)... } } template <class Visitor, class Variant> auto visit(Visitor visitor, Variant&& variant) { return visit_impl(visitor, variant, std::make_index_sequence<std::variant_size_v<Variant>>{}); } This poses an interesting challenge - how close can we get to generically generating something that optimizes to equivalently good assembly as a hand-written switch would?And perhaps even more interestingly: Can C++26 features help with this?Jump TablesSome programming languages provide a direct or indirect way of generating what’s called a jump table or branch table. While C++’s switch statements are not required to be turned into jump tables by the compiler, most compilers will do so if the number of cases is large enough and optimization is enabled.For simplicity let’s not care about a generic visitor just yet, let’s instead always call an undefined template function h:1 2 template <int> int h(); Since it is not defined compilers cannot possibly inline calls to it. This should come in handy once we look at the generated assembly (and optimization passes) to see if compilers were able to understand our code.Consider a simple switch such as:1 2 3 4 5 6 7 8 9 10 int mersenne(unsigned index){ switch (index) { case 0: return h<2>(); case 1: return h<3>(); case 2: return h<5>(); case 3: return h<7>(); case 4: return h<13>(); default: return -1; } } With optimizations enabled, GCC turns this into the following x86 assembly:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 mersenne(unsigne...
First seen: 2025-05-14 22:36
Last seen: 2025-05-15 06:37