Template meta-programming: Wrong number of template arguments in Paramater Pack

Viewed 81

I'm trying to implement a list using Template meta-programming but without success compiling the next code:

#include <iostream>

template<int Value>
struct Int {
    static constexpr int value = Value;
};

template<typename H, typename ...TT>
struct List {
    typedef H head;
    typedef List<TT...> next; // <-- Too few template arguments for class template 'List'
    constexpr static int size = sizeof...(TT) + 1;
};

int main() {
    typedef List<Int<1>, Int<2>, Int<3>> list1;
    static_assert(list1::head::value == 1, "Failed"); // = Int<1>
    static_assert(list1::size == 3, "Failed"); // = 3

    typedef typename list1::next list1Tail; // = List<Int<2>, Int<3>>
    static_assert(list1Tail::head::value == 2, "Failed");
    static_assert(list1Tail::size == 2, "Failed"); // = 2

    typedef typename list1Tail::next list2Tail; // = List<Int<3>> <<---error: wrong number of template arguments (0, should be at least 1)
    static_assert(list2Tail::head::value == 3, "Failed");
    static_assert(list2Tail::size == 1, "Failed");

    std::cout << "Passed" << std::endl;
}

With an error:

In instantiation of ‘struct List<Int<3> >’: error: wrong number of template arguments (0, should be at least 1)

I understand that in my case List must handle two types H and ...TT, but:

  1. Why calling List<TT...> isn't enough?
  2. How should I fix it?
  3. What is the best approach in this case for compiling the code?
4 Answers

On the last step List<TT...> will instantiate specialization List<> which is not defined in your code. You should write a "terminating" specialization as well:

template<typename H>
struct List<H> {
    typedef H head;
    typedef void next;
    constexpr static int size = 1;
};

online compiler

You need a specialization for an empty list or a list with a single element. One possibility is to first declare a fully variadic template, and then create two specializations:

template <typename...>
struct List;

template <typename H, typename... TT>
struct List<H, TT...> {
    using head = H;
    using next = List<TT... >;
    constexpr static int size = sizeof... (TT) + 1;
};

template <>
struct List<> {
    constexpr static int size = 0;
};

This way you can have an empty list List<> which you cannot have with your current version.

Provide a specialization for one element so you don't try to instantiate a List with an empty pack.

template <class H>
struct List<H>
{
    typedef H head;
    constexpr static int size = 1;
};

Variant of the Holt's solution: instead of a second specialization, the ground case of the recursion can be the main template

template <typename...>
struct List
 { constexpr static int size = 0; };

template<typename H, typename ...TT>
struct List<H, TT...> {
    using head = H;
    using next = typedef List<TT...>; 
    constexpr static int size = sizeof...(TT) + 1;
};

Unfortunately is less readable.

Related