[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 ***