C++26: pack indexing

submited by
Style Pass
2025-01-22 19:00:07

C++11 introduced parameter packs to provide a safer way to pass an undefined number of parameters to functions instead of relying on variadic functions.

While packs are a useful feature, and since C++17 it’s so easy to use them in fold expressions, extracting a specific element of a pack is somewhat cumbersome.

You either have to rely on some standard functions not made for the purpose or use “awkward boolean expression crafting or recursive templates”. None of them is unbearable, but it might be error-prone or simply expensive regarding compile-time performance. Nevertheless, they are not the most readable solutions.

We can observe that we can use indexes both with the types and with the values and we can use anything that can be evaluated at compile time. With that, I refer to the fact, that we can get the type or value of the last element by using sizeof...(expr)-1.

P2662R3 is a long but interesting proposal. It discusses several alternative syntaxes for pack indexing and mentions that in fact several people independently came to the same conclusion regarding syntax, which is also proposed by this paper.

Leave a Comment