ProblemsTemplatesThe N-th type of a pack
IntermediateTemplates

The N-th type of a pack

Context

Tuple, variant and function-trait machinery all need the same primitive: take the I-th type out of a pack. There is no pack indexing in the language — you walk the pack by peeling one type per step. The error case matters as much as the happy path: an out-of-range index must not silently produce something.

Task

Implement NthType<I, Ts...>::type — the I-th type of the pack (zero-based). NthType<1, int, double, char> is double. Asking for an index past the end must be a COMPILE error, not a fallback type.

Constraints

  • NthType<0, Ts...>::type is the first type; indices are zero-based
  • Works for any pack length and any I within range
  • I out of range (or an empty pack): instantiating ::type must NOT compile
  • Pure compile time, no values

Before you code

  • How does partial specialization peel exactly one type per recursion step?
  • Why does the out-of-range case end up as a missing definition — and what error does that give?
  • Where does std use this shape? (std::tuple_element)

Tests

  • #1Indexing within range
  • #2Out-of-range index does not compile(expects compile error)
  • #3Empty pack does not compile(expects compile error)

Hints

Hint 1

Two specializations are enough: I == 0 takes the head; any other I drops the head and asks for I - 1.

Hint 2

Leave the primary template declared but undefined — running out of types then hits it and fails to compile, exactly as required.

Editornth-type.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.