声明不带参数的模板结构

时间:2018-01-23 17:31:35

标签: c++ templates

我有一个列表的实现:

template<typename T, typename... TT>
struct List {
    typedef T head;
    typedef List<TT...> next;
    enum { size = sizeof...(TT)+1 };
};

template<typename T>
struct List<T> {
    typedef T head;
    typedef NIL next;
    enum { size = 1 };
};

我正在尝试添加此内容:

template <>
struct List {
    typedef NIL head;
    enum { size = 0 };
};

这样我就可以声明一个空列表:

List<>

当我尝试添加此项时,我收到错误:

error: explicit specialization of non-template 'List'

我该如何解决?

2 个答案:

答案 0 :(得分:4)

您的主要模板应为:

template<typename ... Ts> struct List;

然后你可以部分专门研究0,1,N个参数。

答案 1 :(得分:1)

只需在主模板中添加一个默认值,我在下面的示例中将NIL更改为void,但它适用于任何类型。

template<typename T = void, typename... TT>
struct List
{
  typedef T head;
  typedef List<TT...> next;
  enum { size = sizeof...(TT)+1 };
};

template<typename T>
struct List<T>
{
  typedef T head;
  typedef void next;
  enum { size = 1 };
};

template<>
struct List<>
{
  typedef void head;
  enum { size = 0 };
};