C++26 pack indexing and more
Dear Reader,
I would like to explore interesting features that will ship with C++26.
One such feature is pack-indexing.
The basic mechanics.
If you have an unexpanded parameter pack Ts..., which consists T0, T1,...,T_{N-1}, you can simply write Ts...[I] to select T_I. I should be constexpr.
Moreover, if you have a pack Is..., for example <5,0,3>, then Ts...[Is]... expands to Ts[5], Ts[0], Ts[3].
#include <print>
#include <tuple>
template<typename... Ts>
constexpr auto first(Ts... args) -> Ts...[0]{
return args...[0];
}
template<typename... Ts>
constexpr auto last(Ts... args) -> Ts...[sizeof...(Ts) - 1]{
return args...[sizeof...(Ts) - 1];
}
template<size_t... Is, typename... Args>
constexpr auto select(Args&&... args){
auto tup = std::forward_as_tuple(args...);
return std::make_tuple(std::get<Is>(tup)...);
}
int main(){
static_assert(first(1, 2, 3, 4, 5) == 1);
static_assert(last(1, 2, 3, 4, 5) == 5);
static_assert(select<2,1,0>(1, 2, 3, 4, 5) == std::tuple{3,2,1});
}
This month, I solved few interesting coding exercises:
- Different ways to filter a container
- Coding Exercise - Grouping lines together
- Constructing a 3D array
- Implementing string and SSO
I want to continue sharing interesting C++/Rust/Zig code snippets, discuss about concurrency, performance aspects.
If you want to help, just hit the Reply button and tell me your C++ story. What are the topics you'd like to read more/nerd out?
Also, I appreciate any help: from finding typos, improving code samples to suggesting new content and even some forms of collaboration.
-- Quasar
Add a comment: