在前面写的例子中,模版参数一般都是 int,或者一个类Teacher,假设我们现在有个需求:模版的参数要是vector,list这种结合类型应该怎么写呢?
//当模版中的类型是 vector ,list 等集合类型的时候的处理。//举例,如下typename T是正常的模版参数,MYContainer是类似vector,map,list之类的集合
template<typename T, template<class> class MYContainer>
//template<typename T, template<typename W> class MYContainer>//这一行和上一行是同样的作用,只是,加了一个W,但是这个W不会使用,只是语法上的要求
class Teacher119 {
public:T m_i;MYContainer<T> m_con;
public://构造方法//在参数化列表中,给m_i赋值。Teacher119(T tt):m_i(tt) {//我们假设 实例化模版的的集合中,是有 push_back方法的for (int i = 10; i < 20;i++) {m_con.push_back(i);//假设真正的容器支持push_back方法,vector,list}}};//解决方案:使用using 给vector起别名
template<typename T>
using MYVec = vector<T, allocator<T>>;void main() {
//使用//按之前的写法应该这样写:但是有build error,//build error原因是:vector有两个参数,一个是类型,另一个是allocator<int>//一般情况下allocator<int>是有默认值的,但是在这种情况下,好像没有默认值//解决方案:使用using 给vector起别名 //Teacher119<int, vector<int>> myobj(10000); build errorTeacher119<int, MYVec> myobj(10000); //验证vector<int > aa = myobj.m_con;for (vector<int>::iterator it = aa.begin();it!=aa.end();it++){cout << *it << " ";}//结果为 10 11 12 13 14 15 16 17 18 19}
map情况下的处理,好像不管咋写都有build error,这块先剩下,如果有网友知道怎么写,请帮忙在留言中指导一下