模板类必须所有的方法定义放到一个文件中。因为模板类不是函数不能单独编译
template<typename T1,typename T2,int T3>
class myext:public mybase<T2>
模板定义两个类型参数T1,T2,定义个非类型参数T3,他在使用期间如同一个常数。这个T3可以用来处理动态数组,并且继承了模板类mybase并且将类型参数T2赋予给他
template<typename T2,int T3>
class myext<int,T2,T3>:public mybase<T2>
模板定义一个类型参数T2,定义一个非类型参数T3,那么这里的T2就代表他是泛型的,而不具体化,但是开始的T1变为了具体化的int,
并且继承了模板类mybase并且将类型参数T2赋予给他
template<typename T1,typename T2,int T3>
void myext<T1,T2,T3>::set(const T1 &in)
这是第一个模板类定义方法的方法
template<typename T2,int T3>
void myext<int,T2,T3>::set(const int &in)
这是第二个模板类定义方法的方法
调用:
myext<string,string,4> test2("test","gaopeng"); 将匹配
template<typename T1,typename T2,int T3> class myext:public mybase<T2>
myext<int,int,10> test1(1,1); 将匹配
template<typename T2,int T3> class myext<int,T2,T3>:public mybase<T2>
具体化过后当然选择的方法是选择匹配程度最高的模板。
下面是具体的测试代码没有实际意义:
-
头文件
-
tmp.h
-
#include<iostream>
-
using namespace std;
-
-
template<typename T1>
-
class mybase
-
{
-
private:
-
T1 a;
-
public:
-
mybase(T1 in)
-
{
-
a=in;
-
}
-
virtual void show(void) const
-
{
-
cout<<a<<endl;
-
}
-
virtual ~mybase(){}
-
};
-
-
template<typename T1,typename T2,int T3>
-
class myext:public mybase<T2>
-
{
-
private:
-
T1 b;
-
public:
-
myext(T1 in1,T2 in2):mybase<T2>(in2)
-
{
-
b=in1;
-
}
-
virtual void show(void) const
-
{
-
for(int i=0;i<T3;i++)
-
cout<<b<<endl;
-
mybase<T2>::show();
-
}
-
virtual ~myext(){}
-
-
virtual void set(const T1&);
-
};
-
-
template<typename T1,typename T2,int T3>
-
void myext<T1,T2,T3>::set(const T1 &in)
-
{
-
b=in;
-
for(int m=0;m<T3;m++)
-
{
-
cout<<"test"<<endl;
-
}
-
}
-
-
template<typename T2,int T3>
-
class myext<int,T2,T3>:public mybase<T2>
-
{
-
private:
-
int b;
-
public:
-
myext(int in1,T2 in2):mybase<T2>(in2)
-
{
-
b=in1+100;
-
}
-
virtual void show(void) const
-
{
-
for(int i=0;i<T3;i++)
-
cout<<b<<endl;
-
mybase<T2>::show();
-
}
-
virtual ~myext(){}
-
virtual void set(const int&);
-
};
-
template<typename T2,int T3>
-
void myext<int,T2,T3>::set(const int &in)
-
{
-
b=in+100;
-
for(int m=0;m<T3;m++)
-
{
-
cout<<"test1"<<endl;
-
}
-
}
-
main函数
-
-
#include<iostream>
-
#include"tmp.h"
-
using namespace std;
-
-
-
int main(void)
-
{
-
cout<<"use specialization template"<<endl;
-
myext<int,int,10> test1(1,1);
-
test1.set(10);
-
test1.show();
-
cout<<"use general template"<<endl;
-
myext<string,string,4> test2("test","gaopeng");
-
test2.show();
-
}
输出:
use specialization template
test1
test1
test1
test1
test1
test1
test1
test1
test1
test1
110
110
110
110
110
110
110
110
110
110
1
use general template
test
test
test
test
gaopeng
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7728585/viewspace-2124228/
,如需转载,请注明出处,否则将追究法律责任。