设为首页 加入收藏

TOP

C++ 基于Policy 的 模板编程
2014-11-23 22:06:50 来源: 作者: 【 】 浏览:8
Tags:基于 Policy 模板 编程

在没真正接触C++ 模板编程之前,真的没有想到C++ 还可以这么用,最大的感触是:太灵活了,太强大了。最初接触模板威力还是在Delta3d中,感觉里面的模板使用实在是灵活与方便,特别是dtAI中使用了大量的模板,大大增强了库的可扩展性。


C语言梳理一下,分布在以下10个章节中:


先看一段代码:


#include
#include
#include
using namespace std;
//--------------------------------------------------------------------------------
/////////Widget类型
class SliderWidget
{
public:
SliderWidget()
{
std::cout<<"Slider Widget created"< }
};


class BoxWidget
{
public:
BoxWidget()
{
std::cout<<"Box Widget created"< }
};
//--------------------------------------------------------------------------------
//创建widget方法


template
class OpNewCreateor
{
public:
static T* create()
{
return new T;
}
protected:
~OpNewCreateor(){}
};


template
class MallocCreator
{
public:
static T* create()
{
void * buf = std::malloc(sizeof(T));
if(!buf) return 0;


return new(buf) T;
}
protected:
~MallocCreator(){}
};


template
class PrototypeCreator
{
public:
PrototypeCreator(T* pObj = 0)
:pPrototype(pObj)
{


}
T* create()
{
return pPrototype pPrototype->clone() : 0;
}
T* getPrototype(){return pPrototype;}
void setPrototype(T*pObj){pPrototype = pObj;}


protected:
~PrototypeCreator(){}
private:
T* pPrototype;
};
//--------------------------------------------------------------------------------
//存储widget容器类型
template
class ContainerVec
{
public:
void push(T* widget)
{
mVecContainer.push_back(widget);
}
//protected://Container 不能是保护类型,因为WidgetManager 不继承此类
~ContainerVec(){}


private:
std::vector mVecContainer;//Vector容器
};


template
class ContainerList
{
public:
void push(T* widget)
{
mListContainer.insert(widget);
}

~ContainerList(){}//Container 不能是保护类型,因为WidgetManager 不继承此类
private:
std::list mListContainer;//List容器
};
//--------------------------------------------------------------------------------
//--------widget管理类
template <
class T,
template class CreationPolicy = MallocCreator,
template class Container = ContainerVec
>
class WidgetManager :public CreationPolicy
{
public:
typedef CreationPolicy BaseClass;
T* create()
{
T* tmp = BaseClass::create();
mContainer.push(tmp);
return tmp;
}



private:
Container mContainer;
};


//--------------------------------------------------------------------------------
typedef WidgetManager BoxWidgetManager;
typedef WidgetManager SliderWidgetManager;
//--------------------------------------------------------------------------------



int main()
{
BoxWidgetManager boxWidgetManager;


BoxWidget * boxWidget = boxWidgetManager.create();



cout << typeid(BoxWidgetManager).name() << endl;



system( "pause");
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇OpenGL 深度缓冲区 Z缓冲区 介绍 下一篇【OpenGL4.0】GLSL渲染语言入门与..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: