C++ C++;用于替换类型列表的可变模板
我想利用可变模板来替换下面的标准类型列表代码。另外,请注意,它使用int作为类型。我试图输入C++11定义的强类型枚举,因此我想用模板参数类型替换int HEADC++ C++;用于替换类型列表的可变模板,c++,c++11,enums,variadic-templates,typelist,C++,C++11,Enums,Variadic Templates,Typelist,我想利用可变模板来替换下面的标准类型列表代码。另外,请注意,它使用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&
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) >
模板
结构IntList{
枚举{head=head};
尾型;
};
结构IntListEnd{};
#定义列表1(a)IntList
#定义列表2(a,b)IntList
#定义列表3(a、b、c)IntList
#定义列表4(a、b、c、d)IntList
以下是我想要走的路:
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 { };
模板
结构列表;
模板
结构列表{
T头=值;
bool hasNext(){
如果(…sizeof(Args)>=0)
返回true;
}
vlist vlist;
vlist getNext(){
返回列表;
}
};
模板
结构vlist{};
初始化此文件的示例应类似于以下内容:
enum class FishEnum { jellyfish, trout, catfish };
vlist <FishEnum, FishEnum::jellyfish, FishEnum::trout, FishEnum::catfish> myvlist;
enum类鱼类enum{水母、鳟鱼、鲶鱼};
vlist 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;
注意:前面的声明“template struct vlist”使用了2个模板参数
模板结构列表;
^
错误:使用1个模板参数重新声明
结构vlist{};
^
注意:前面的声明“template struct vlist”使用了2个模板参数
模板结构列表;
基本模板缺少许多参数扩展和专门化。需要记住的一点是:一旦声明了基础模板,所有其他模板都必须是该基础的专门化:
// 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...>();
}
};
//基本模板
模板
结构列表;
//为一个值专门化
模板
结构列表
{
T头=头;
constexpr bool有_next()const{return false;}
};
//可变特化
模板
结构列表
{
T头=值;
constexpr bool有_next()const{return true;}
constexpr vlist next()常量
{
返回vlist();
}
};