CodeBlanks Logo Icon CodeBlanks

Type lists

Learn compile-time lists with type lists.

Type lists

A type list is a data structure that stores types at compile time. It is written with a variadic template: template <typename... Ts> struct Typelist {};. Here Ts is a parameter pack of types.

The length is computed at compile time with a recursive helper. The empty list has length 0; a non-empty list has length 1 + Length<tail>::value. So for Typelist<int, double, char> the length is 3.

The Length helper

Length returns how many types a Typelist holds. The general specialization peels the head and calls Length on the rest: template <typename Head, typename... Tail> struct Length<Typelist<Head, Tail...>> { static const int value = 1 + Length<Typelist<Tail...>>::value; };.

For the empty list template <> struct Length<Typelist<>> { static const int value = 0; };. This has the same shape as the recursive Factorial; it just works on a list of types.

Practice Write Typelist and Length

Define template <typename... Ts> struct Typelist {};. Write the general Length specialization with 1 + Length<Typelist<Tail...>>::value. Add the empty specialization with value = 0. In main write std::cout << Length<Typelist<int, double, char>>::value;.

Starter code

main.cpp
#include <iostream>

// Define Typelist and Length templates here

int main() {
    // Print the length result
    return 0;
}

Sample solution

main.cpp
#include <iostream>

template <typename... Ts>
struct Typelist {};

template <typename List>
struct Length;

template <typename Head, typename... Tail>
struct Length<Typelist<Head, Tail...>> {
    static const int value = 1 + Length<Typelist<Tail...>>::value;
};

template <>
struct Length<Typelist<>> {
    static const int value = 0;
};

int main() {
    std::cout << Length<Typelist<int, double, char>>::value;
    return 0;
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
typename... Ts Parameter pack
struct Typelist List structure
Length<Typelist<...>> Compile-time length
Typelist<int, char> Two types

2 Empty list length

Question
template <> struct Length<Typelist<>> { static const int value = ____; };
Answer
template <> struct Length<Typelist<>> { static const int value = 0; };

Explanation: The empty list has length 0.

3 Length of Typelist<int, double, char>?

main.cpp
template <typename... Ts> struct Typelist {};
template <typename Head, typename... Tail> struct Length<Typelist<Head, Tail...>> { static const int value = 1 + Length<Typelist<Tail...>>::value; };
  • 1
  • 6
  • 0
  • 3 Correct answer

Explanation: int, double and char are three types; length is 3.

All lessons in Expert