1

I have come across this code in this answer and I can not explain what it does exactly and how I might use it as a compile time sequence of integers.

template <size_t ...I>
struct index_sequence {};

template <size_t N, size_t ...I>
struct make_index_sequence : public make_index_sequence<N - 1, N - 1, I...> {};

template <size_t ...I>
struct make_index_sequence<0, I...> : public index_sequence<I...> {};

I have found similar implementations before, namely here and here, but never knew how to understand the syntax. I don´t understand the two template struct definitions for make_index_sequence, in particular the parts with public (e.g. : public make_index_sequence<N - 1, N - 1, I...>). May someone explain this to me?

Is there any inheritance happening here? How does the recursion work? Where is the sequence stored?

EDIT: An example usage for an integer sequence generated by these templates is to generate indices for accessing a std::tuple<>. The generator will generate an index for each element in the tuple at compile time.

stimulate
  • 1,199
  • 1
  • 11
  • 30
  • The `: public` part is a hint that inheritance is going on. Why you'd do this I'm not sure. What's your goal? – tadman Sep 03 '17 at 23:35

1 Answers1

1

Is there any inheritance happening here?

Yes:

template <size_t N, size_t ...I>
struct make_index_sequence : public make_index_sequence<N - 1, N - 1, I...> 
                        // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The struct make_index_sequence<N,...> inherits struct make_index_sequence<N-1,N-1,...>.

How does the recursion work?

By inheritance and providing another part of the variadic template parameter pack.

The recursion stops when the specialization for N==0 is met.

Where is the sequence stored?

At the variadic template parameter pack of template <size_t ...I> struct index_sequence {};

user0042
  • 7,917
  • 3
  • 24
  • 39
  • When is the `template struct make_index_sequence` first generated (or encountered/processed)by the compiler? Does the struct inherit from itself or is it somehow "overloaded"? – stimulate Sep 03 '17 at 23:40
  • @stimulate You know what template instantiation and specialization does, do you? `make_index_sequence` inherits by another instantiation of itself, and has a specialization for the `N=0` case. – user0042 Sep 03 '17 at 23:42