C++ Templates 第十六章 模板与继承 例子
[cpp]#include <iostream>
using namespace std;
// 中间模板
template <typename Base, int D>
class Discrim : public Base
{
public:
Discrim() {
cout<<"Discrim()"<<endl;
}
};
// 类Discrim 使的 PolicySelector 可以多次继承自相同的基类
template <typename set1, typename set2, typename set3, typename set4>
class PolicySelector : public Discrim<set1, 1>, public Discrim<set2, 2>, public Discrim<set3, 3>, public Discrim<set4, 4>
{
};
class DefaultPol1 {
public:
void print() {
cout<<"p1 print()"<<endl;
}
};
class DefaultPol2 {
public:
void print() {
cout<<"p2 print()"<<endl;
}
};
class DefaultPol3 {
public:
void print() {
cout<<"p3 print()"<<endl;
}
};
class DefaultPol4 {
public:
void print() {
cout<<"p4 print()"<<endl;
}
};
// 建立一个缺省值的集合
class DefaultPols
{
public:
typedef DefaultPol1 dp1;
typedef DefaultPol2 dp2;
typedef DefaultPol3 dp3;
typedef DefaultPol4 dp4;
};
class DefaultPolArgs : virtual public DefaultPols {};
// 写几个模板覆盖缺省的policy参数
// 1
template <typename Policy>
class Policy1_is : virtual public DefaultPols
{
public:
typedef Policy dp1;
virtual void print() {
dp1 dd;
dd.print();
}
};
// 2
template <typename Policy>
class Policy2_is : virtual public DefaultPols
{
public:
typedef Policy dp2;
virtual void print() {
dp1 dd;
dd.print();
}
};
// 3
template <typename Policy>
class Policy3_is : virtual public DefaultPols
{
public:
typedef Policy dp3;
Policy3_is() {
cout<<"Policy3_is()"<<endl;
}
virtual void print() {
dp1 dd;
dd.print();
}
};
// 4
template <typename Policy>
class Policy4_is : virtual public DefaultPols
{
public:
typedef Policy dp4;
virtual void print() {
dp1 dd;
dd.print();
}
};
// 这里所有的默认值相同
template <typename PolicySet1 = DefaultPolArgs,
typename PolicySet2 = DefaultPolArgs,
typename PolicySet3 = DefaultPolArgs,
typename PolicySet4 = DefaultPolArgs>
class BreadSlicer
{
public:
// 创建选择器,PolicySelector 在这里用模板参数分别初始化为对应的类型
// 这样就指定了 PolicySelector 的父类, 从别从自个模板参数中继承而来。。。
// 这一块的理解还不是很清楚??
typedef PolicySelector<PolicySet1, PolicySet2, PolicySet3, PolicySet4> policies;
void print() {
typename policies::dp1 p1;
p1.print();
typename policies::dp2 p2;
p2.print();
typename policies::dp3 p3;
p3.print();
typename policies::dp4 p4;
p4.print();
}
};
class CustomPoliA
{
public:
void print() {
cout<<"CustomPoliA print()"<<endl;
}
};
class CustomPoliB
{
public:
void print() {
cout<<"CustomPoliB print()"<<endl;
}
};
int main(int argc, char **argv)
{
BreadSlicer<Policy3_is<CustomPoliA>, Policy4_is<CustomPoliB> > bc;
bc.print();
return 0;
}
Starting: /home/robertkun/projects/tevent/build/tevent
p1 print()
p2 print()
CustomPoliA print()
CustomPoliB print()
*** Exited normally ***
补充:软件开发 , C++ ,