C++: TypeList

本文介绍了一个使用C++模板元编程实现的基本类型列表处理系统。该系统包括类型列表的定义、获取列表长度、按索引获取类型、查找类型的索引以及列表的追加操作。通过具体的代码示例展示了如何定义类型列表并进行各种操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <typeinfo.h>
//
// TypeList
//
template <class T, class U>
struct TypeList
{
    typedef T Head;
    typedef U Tail;
};

struct NullType
{
};

#define TYPELIST_1(T1)            TypeList<T1, NullType>
#define TYPELIST_2(T1, T2)        TypeList<T1, TYPELIST_1(T2) >
#define TYPELIST_3(T1, T2, T3)    TypeList<T1, TYPELIST_2(T2,T3) >

//
// Length
//
template <class TList>  struct Length;

template <>  struct Length<NullType >
{
    enum {value = 0};
};

template <class T,class U>  
struct Length<TypeList<T,U> >
{
    enum {value = 1 + Length<U>::value};
};

//
// TypeAt
//
template <class TList, unsigned int index>  struct TypeAt;

template <class Head, class Tail>  struct TypeAt< TypeList<Head,Tail>,0 >
{
    typedef Head Result;
};

template <class Head, class Tail, unsigned int index>  struct TypeAt< TypeList<Head,Tail>,index >
{
    typedef typename TypeAt<Tail, index-1>::Result Result;
};

//
// IndexOf
//
template <class TList, class T>  struct IndexOf;

template <class T>  struct IndexOf< NullType, T >
{
    enum {value = -1};
};
template <class T,class Tail>  struct IndexOf< TypeList<T, Tail>, T >
{
    enum {value = 0};
};

template <class Head,class Tail, class T>  struct IndexOf< TypeList<Head, Tail>, T >
{
private:
    enum { temp = IndexOf<Tail,T>::value };
public:
    enum { value = temp==-1 ? -1 : 1 + temp};
};


//
// Append
//
template <class TList, class T>  struct Append;

//
// push_front
//
template <class TList, class T>  struct push_front
{
    typedef TypeList<T, >
};

int main(int argc, char *argv[])
{
    printf("Hello, world\n");

    typedef TYPELIST_3(int, float,char) MyTypeList;
    printf("MyTypeList length %d\n", Length<MyTypeList>::value);

    printf("MyTypeList TypeAt 0 %s\n", typeid(TypeAt<MyTypeList,0>::Result).name());
    printf("MyTypeList IndexOf<int> %d\n", IndexOf<MyTypeList, float>::value);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值