简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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