Skip to content

Latest commit

 

History

History
73 lines (51 loc) · 1.7 KB

358.md

File metadata and controls

73 lines (51 loc) · 1.7 KB
Info

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));

https://circle.godbolt.org/z/f1Pav4e9x

Puzzle

  • Can you implement first and last 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));

https://circle.godbolt.org/z/6cxxdos9r

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));

https://godbolt.org/z/bc71YxGY1

// 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, ...); }

https://circle.godbolt.org/z/d7K35shjh