c++ 泛型程式設計 之 自動生成程式碼

Sunday發表於2015-02-25

 http://download.csdn.net/detail/zhuyingqingfen/8457091

關於 C++ 泛型中的 TypeList ,參考  c++ 泛型程式設計 之 TypeLists


#ifndef GENSCATTERHIERARCHY_H_
#define GENSCATTERHIERARCHY_H_
#include "typelists.h"
#include "typetraits.h"


#if defined(_MSC_VER) && _MSC_VER >= 1300
// 'class1' : base-class 'class2' is already a base-class of 'class3'
#pragma warning( disable : 4584 )
#endif // _MSC_VER


//運用Typelists 自動產生Classes

//1. 產生“散亂的繼承體系”(scattered hierarchies)
template<class TList,template<class>class Unit>class GenScatterHierarchy;

template<class T1,class T2,template<class>class Unit>
class GenScatterHierarchy<Typelist<T1,T2>,Unit>//如果第一個型別是TypeList,就遞迴產生GenScatterHierarchy<TList::Head,Unit>
	:public GenScatterHierarchy<T1,Unit>//和GenScatterHierarchy<TList::Tail,Unit>,並繼承二者。
	,public GenScatterHierarchy<T2,Unit>
{
public:
	typedef Typelist<T1, T2> TList;
	typedef GenScatterHierarchy<T1, Unit> LeftBase;
	typedef GenScatterHierarchy<T2, Unit> RightBase;
};

template<class AtomicType,template<class>class Unit>//如果第一個型別是個單一型別(ActomicType,相對於Typelist
class GenScatterHierarchy : public Unit<AtomicType>// GenScatterHeierarchy便把該型別傳遞給Unit,然後繼承Unit<T>
{
public:
	typedef Unit<AtomicType> LeftBase;
};
template<template<class> class Unit>
class GenScatterHierarchy<NullType,Unit>//空類
{

};

//2. 產生線性繼承體系。
//1. 要求這個Unit有兩個引數
//2. 要求Unit繼承於Unit的第二個引數Base,這樣GenLinearHierarchy才能生成串狀繼承結構
template<
	class TList,
	template<class AtomicType,class Base>class Unit,
	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<T,NullType>,Unit,Root>
	:public Unit<T,Root>
{

};

//GenScatterHierarchy的訪問輔助類
template<class TList,template<class>class Unit>
Unit<typename TList::Head>&FieldHelper(GenScatterHierarchy<TList, Unit>&obj,Int2Type<0>)
{
	GenScatterHierarchy<typename TList::Head,Unit>&leftBase = obj;
	return leftBase;
}
template<int i,class TList,template<class>class Unit>
Unit<typename TypeAt<TList,i>::Result>& FieldHelper(GenScatterHierarchy<TList,Unit>&obj,Int2Type<i>)
{
	GenScatterHierarchy<typename TList::Tail,Unit>& rightBase = obj;
	return FieldHelper(rightBase,Int2Type<i-1>());
}
template<int i,class TList,template<class>class Unit>
Unit<typename TypeAt<TList,i>::Result>&Field(GenScatterHierarchy<TList,Unit>&obj)
{
	return FieldHelper(obj,Int2Type<i>());
}

#endif


template<class T>
struct Holder
{
	T mValue;
}; 
void hierarchygenerators_Test()
{
	//GenScatterHierarchy
	typedef GenScatterHierarchy<TYPELIST_4(char,int,string,string),Holder> MyTestClass;
	MyTestClass obj;
	Field<0>(obj).mValue = 'a';
	int i = Field<1>(obj).mValue;
	typedef TYPELIST_2(int,int) f;
	//GenLinearHierarchy 
}


相關文章