C++
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.
Exercise 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;.
Show example solution
#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;
}
Test yourself
-
Match each piece to its role
- typename... Ts
- Parameter pack
- struct Typelist
- List structure
- Length<Typelist<...>>
- Compile-time length
- Typelist<int, char>
- Two types
-
Empty list length
template <> struct Length<Typelist<>> { static const int value = ____; };
Show answer
template <> struct Length<Typelist<>> { static const int value = 0; };
-
Length of Typelist<int, double, char>?
template <typename... Ts> struct Typelist {};
template <typename Head, typename... Tail> struct Length<Typelist<Head, Tail...>> { static const int value = 1 + Length<Typelist<Tail...>>::value; };
Show answer
3 — int, double and char are three types; length is 3.
Next lesson: constexpr functions