#include <iostream>
using namespace std;
//当CD不使用模板参数时填充此类
class CNull
...{
public:
static CNull* instance()
...{
return &m_oCNull;
}
private:
static CNull m_oCNull;
};
CNull CNull::m_oCNull;
class CA
...{
public:
static CA* instance()
...{
return &m_oCA;
}
void f1()
...{
//do something...
cout << "CA.f1()" << endl;
}
private:
static CA m_oCA;
};
CA CA::m_oCA;
class CB
...{
public:
static CB* instance()
...{
return &m_oCB;
}
void f2()
...{
//do something...
cout << "CB.f2()" << endl;
}
private:
static CB m_oCB;
};
CB CB::m_oCB;
class CC
...{
};
//此类有两个模板参数
template <class T1, class T2>
class CD
...{
public:
CD()
...{
m_pT1 = T1::instance();
m_pT2 = T2::instance();
}
~CD()
...{
m_pT1 = NULL;
m_pT2 = NULL;
}
T1* getT1()
...{
return m_pT1;
}
T2* getT2()
...{
return m_pT2;
}
private:
T1* m_pT1;
T2* m_pT2;
};

int main()
...{
//当两个模板参数都被使用时
CD<CA, CB> d;
d.getT1()->f1(); //因为CA有函数f1,所以成功
d.getT2()->f2(); //因为CB有函数f2,所以成功
//当只有一个模板参数被使用时,将第二个参数设为CNull
CD<CA, CNull> d2;
d2.getT1()->f1(); //因为CA有函数f1,所以成功
d2.getT2()->f2(); //因为CNull没有函数f2,所以编译时出错
//当错误的使用了不带instance函数的类CC时,会编译时出错
CD<CC, CC> d3;
return 0;
}
本文介绍了一个使用C++模板元编程实现的示例,通过定义多个类并利用模板类CD来组合这些类的实例,展示了如何在编译时进行类型配置。具体实现了根据不同模板参数实例化不同的类,并提供了调用这些类成员函数的方法。
803

被折叠的 条评论
为什么被折叠?



