首页 > 代码库 > 读loki有感,TYPEList原理
读loki有感,TYPEList原理
读loki有感,TYPEList原理
问题一,简化版的TYPEList,只支持int型
template<int n>
class TYPEList
{
public:
int Head;
TYPEList<n-1> Tail;
};
template<>
class TYPEList<0>
{
public:
int Tail;
int Head;
};
测试代码
TYPEList<0> l0;
l0.Head = 1;
l0.Tail = 2;
TYPEList<2> l2;
l2.Head = 3;
l2.Tail.Head = 4;
l2.Tail.Tail.Head = 5;
l2.Tail.Tail.Tail = 6;
问题二:可以同过GetAt(int)获取值
template<int n>
class TYPEList
{
public:
int Head;
TYPEList<n-1> Tail;
int GetAt(int index )
{
if( n+1 == index )
return Head;
return Tail.GetAt(index);
}
};
template<>
class TYPEList<0>
{
public:
int GetAt(int index)
{
if( 1 == index )
return Tail;
return Head;
}
int Tail;
int Head;
};
测试代码
TYPEList<0> l0;
l0.Head = 1;
l0.Tail = 2;
TYPEList<2> l2;
l2.Head = 3;
l2.Tail.Head = 4;
l2.Tail.Tail.Head = 5;
l2.Tail.Tail.Tail = 6;
int i1 = l2.GetAt(0);
int i2 = l2.GetAt(1);
int i3 = l2.GetAt(2);
int i4 = l2.GetAt(3);
问题三,类型不再限于int,但最多集成3个变量。
class NullType
{
};
template <class T, class U>
struct Typelist
{
T Head;
U Tail;
};
template <typename T1 = NullType, typename T2 = NullType, typename T3 = NullType >
struct MakeTypelist
{
private:
typedef typename MakeTypelist< T2 ,T3>::Result TailResult;
public:
typedef Typelist<T1, TailResult> Result; };
template<>
struct MakeTypelist<>
{
typedef NullType Result;
};
测试代码:
MakeTypelist<ULONG,CString,int>::Result User,User2;
User.Head = 1;
User.Tail.Head = "何志丹";
User.Tail.Tail.Head = 35;
User2 = User;
template <class AtomicType, template <class> class GenFunc>
struct IterateTypes
{ template<class II>
void operator()(II ii)
{
GenFunc<AtomicType> genfunc;
*ii = genfunc();
++ii; //Is this even needed?
}
};
读loki有感,TYPEList原理