Example
template<auto N> consteval auto nth(auto... ts) { return ts...[N]; }
static_assert(1 == nth<0>(1, 2, 3));
static_assert(2 == nth<1>(1, 2, 3));
static_assert(3 == nth<2>(1, 2, 3));
Puzzle
- Can you implement
first
andlast
with Pack Indexing feature and without it?
consteval auto first(auto... ts); // TODO
consteval auto last(auto... ts); // TODO
static_assert(1 == first(1, 2, 3));
static_assert(3 == last(1, 2, 3));
Solutions
template <size_t Index, class T0, class... Types>
constexpr decltype(auto) nth(T0&& p0, Types&&... pack) noexcept
{
if constexpr (0 == Index)
return std::forward<T0>(p0);
else
return nth<Index-1>(std::forward<Types>(pack)...);
}
consteval auto first(auto... ts) {
return nth<0>(ts...);
}
consteval auto last(auto... ts) {
return nth<sizeof...(ts) - 1>(ts...);
}
static_assert(1 == first(1, 2, 3));
static_assert(3 == last(1, 2, 3));
// pack indexing
consteval auto first(auto... ts) { return ts...[0]; }
consteval auto last(auto... ts) { return ts...[sizeof...(ts)-1]; }
// Without pack indexing
consteval auto first(auto... ts) { return [](auto first, auto...) { return first; }(ts...); }
consteval auto last(auto... ts) { return (ts, ...); }