loki 提供一个极具威力的工具,可轻易将typelist里的每一个型别套用于一个由用户提供的基本template身上
这么一来将typelist 内的型别分发至客端代码的一些不便过程就被完全封装在loki程序库中,使用者只需自行定义一个单一template
template <class TList,template <class>class Unit>
class GenScatterHierarchy;
template <class T1,class T2,template <class >class Unit>
class GenScatterHierarchy<TYPELIST_2(T1,T2),Unit>;public GenScatterHierarchy<T1,Unit>,public GenScatterHierarchy<T2,Unit>
{
};
template <class AtomicType,template <class>class Unit>
class GenScatterHierarchy:public Unit<ActomicType>
{
};
template <template<class>class Unit>
class GenScatterHierarchy<NullType,Unit>
{
};
最终一一具现体
template <class T>
struct Holder
{
T value_;
}
typedef GenScatterHierarchy<TYPELIST_3(int,string,Widget),Holder>WidgetInfo;
根据型别取成员变量
template <class T,class TList,template <class>class Unit>
Unit <T>&Field (GenScatterHierarchy<TList,Unit>&obj)
{
return obj;
},
自动继承,注意符号相同会隐藏,typelist中不能有重复型别时
解决方式
我们需要一个“以索引选择GenSCatterHierarchy”实体栏位的方法,引导继承的方式
template <class TList,tempate<class>class Unit>
Unit<TList::Head>& FieldHelper(
GenSatterHierarchy<TList,Unit>&obj,Int2Type<0>)
{
GenScatterHierarchy<TList::Head,Unit>& leftBase= obj;
return leftBase;
}
template <int i ,class TList,template<class>class Unit>
Unit<TypeAt<TList,index>::Result>&
FieldHelper(
GenScatterHierarchy<TList,Unit>& obj,
Int2Type<i>)
{
GenScatterHierarchy<TList::Tail,Unit>& rightBase=obj;
return FieldHelper(rightBase,Int2Type<i-1>());
}
template <int i ,class TList,Template <class>class Unit>
Unit <TypeAt<TList,index>::Result>&
Field(GenScatterHierarchy<TList,Unit>&obj)
{
return FieldHeler(obj,Int2Type<i>());
}
如此可以通过索引
WidgetInfo obj;
int x= Field<0>(obj).value_;
int y= Field<1>(obj).value_;
tuples
template <class T>
struct Holder
{
T value_
}
typedef GenScatterHierarchy<
TYPELIST_3(int,int,int),Holder>
Point3D;
Loki定义的Tuple temPplate class 可以直接访问&value,不需要从对象间接访问value
example
typedef Tuple<TYPELIST_3(int,int,int)> Point3D;
Point3D pt;
Field<0>(pt)=0;
Field<1>(pt)=100;
Field<2>(pt)=300;
获取值
Tuple<TYPELIST_3(int,int,int)>
GetWindowPlacement(Window&);
单线继承方式
template
<
calss TList;
template <class AtmoicType,class Base>class Uint,class Root= EmptyType
>
class GenLinearHierarchy;
template
<
class T1,
class T2,
template<class ,class>class Unit,
class Root
>
class GenLinearHierarchy<Typelist<T1,T2>,Unit,Root>
:public Unit<T1,GenLinearHierarchy<T2,Unit,Root>>
{
};
template
<
class T,
template<class ,class>class Unit,
class Root
>
class GenLinearHierarchy<TYPELIST_1(T),Unit,Root>
:public Unit<T,Root>
{
};
template<class T,class Base>
class EventHandle:public Base
{
public:
virtual void onEvent(T &obj,int eventId);
}
typedef GenLinearHierarchy
<
TYPELIST_3(Window,Button,ScrollBar),
EventHandler
>
MyEventHanldr;
Over!