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



我想利用可变参数模板来替换下面的标准字体列表代码。 另外,请注意,这使用 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 { };

初始化这个的示例应该类似于下面:

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;

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

// 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...>();
    }
};

最新更新