C++可变参数模板替代类型列表

3
我希望使用可变参数模板来替换下面的标准类型列表代码。请注意,这里使用int作为类型。我正在尝试将C++11定义的强类型枚举合并进来,所以我想用一个模板参数类型来替换int HEAD。
template <int HEAD, class TAIL>
struct IntList {
  enum { head = HEAD };
  typedef TAIL tail;
};

struct IntListEnd {};

#define LIST1(a) IntList<a,IntListEnd>
#define LIST2(a,b) IntList<a,LIST1(b) >
#define LIST3(a,b,c) IntList<a,LIST2(b,c) >
#define LIST4(a,b,c,d) IntList<a,LIST3(b,c,d) >

以下是我想要探讨的道路:

template <class T, T... Args> 
struct vlist;

template <class T, T value, T... Args>
struct vlist {
  T head = value;
  bool hasNext() { 
    if (...sizeof(Args) >=0 ) 
      return true; 
  }
  vlist<T,Args> vlist;
  vlist getNext () { 
    return vlist;
  }
};

template <class T> 
struct vlist { };

以下是初始化 I 的示例:

enum class FishEnum { jellyfish, trout, catfish };
vlist <FishEnum, FishEnum::jellyfish, FishEnum::trout, FishEnum::catfish> myvlist;

我在论坛上搜索了一个可以接受类型和类型值的模板结构的好例子,但没有找到。有什么建议吗?我已经粘贴了上面代码的编译错误如下:

note: previous declaration 'template<class T, T ...Args> struct vlist' used 2 template parameters
template <class T, T... Args> struct vlist;
                                     ^
error: redeclared with 1 template parameter
struct vlist { };
       ^
note: previous declaration 'template<class T, T ...Args> struct vlist' used 2 template parameters
template <class T, T... Args> struct vlist;
1个回答

7

您缺少基本模板的许多参数扩展和特殊化。需要记住的一件事是: 一旦您声明了基本模板,所有其他模板都必须是该基本模板的特殊化

// Base template
template <class T, T... Args> 
struct vlist;

// Specialization for one value
template <typename T, T Head>
struct vlist<T, Head>
{
    T head = Head;
    constexpr bool has_next() const { return false; }
};

// Variadic specialization
template <class T, T Value, T... Args>
struct vlist<T, Value, Args...> 
{
    T head = Value;

    constexpr bool has_next() const { return true; }

    constexpr vlist<T, Args...> next() const
    { 
        return vlist<T, Args...>();
    }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接