简体   繁体   English

用于替换typelist的C ++可变参数模板

[英]C++ variadic template to replace typelist

I would like to utilize variadic templates to replace this below standard typelist code. 我想利用可变参数模板来替换下面的标准类型列表代码。 Also, note, this uses int as the type. 另外,请注意,这使用int作为类型。 I am trying to incorperate strongly typed enums as defined by C++11 so i want to replace the int HEAD with a template parameter type. 我试图加入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) >

Here is what the road I was trying to go down: 这就是我试图走下去的道路:

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 { };

And an example of initializing this I should be similar to the below: 初始化这个的例子我应该类似于下面的:

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

I have searched the forums of a good example of a template struct that can accept the type and the type values without luck. 我在论坛上搜索了一个模板结构的好例子,它可以接受类型和类型值而没有运气。 Any suggestions on where to go from here? 关于从哪里去的任何建议? I have pasted my compilation errors below from the above code, 我在上面的代码中粘贴了下面的编译错误,

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;

You're missing a number of parameter expansions and specializations for the base template. 您缺少基本模板的许多参数扩展和特化。 One thing to keep in mind: once you have declared the base template, all other templates must be specializations of that base: 有一点要记住:一旦你声明的基础模板,所有其他模板必须是基础的专业

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM