Get the latest tech news

Variadic Switch


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: ```c++ template <class Visitor, class Variant, std::size_t … Is> auto visit_impl(Visitor visitor, Variant && variant, std::index_sequence) { auto i = variant.index(); switch (i) { (case Is: return visitor(get(variant));)... } }

While it won’t help with solving the stated problem, we can approximately work backwards from the generated assembly by using GCC’s computed goto extension. To reduce the amount of branches that need to be discarded as much as possible, we can generate multiple explicit specializations of a class template that handle variants up to a specific size limit each. However, as we’ve already proven with the fold tricks, clang (and gcc for that matter) are perfectly capable of optimizing multiple branches into a jump table for us.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of Variadic Switch

Variadic Switch