一个模板中可以具有多个参数,即可以在一个模板中声明多个自定义的类型,如下面这句话:
template < class T1, class T2>
|
而我们就可以利用这两个参数声明一个具有2种类型的成员。下面我用一个程序说下演示一下这个问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream>
#include <string>
using namespace std;
template < class T1, class T2>
class show
{
public :
void show1(T1 &a){cout<< "show1:" <<a<<endl;}
void show2(T2 &a){cout<< "show2:" <<a<<endl;}
};
int main()
{
show< int ,string> a;
int temp1=5;
string temp2= "Hello,C++!" ;
a.show1(temp1);
a.show2(temp2);
return 0;
}
|
在上面的程序中,我在主函数中将两个类型T1和T2分别设置成了int型和string类型。这样一来,我们在程序的第15行和16行定义的整型变量和string型变量就可以在17行和18行被输出,结果如下:

另外一个需要注意的问题,我们也可以为模板参数提供默认的类型,比如说:
template < class T1, class T2=string>
|
这样一来,我们就把T2参数默认设置成了string类型。那么在上面主程序中,我们把14行换成:
这样还是相当于:
整个程序示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream>
#include <string>
using namespace std;
template < class T1, class T2=string>
class show
{
public :
void show1(T1 &a){cout<< "show1:" <<a<<endl;}
void show2(T2 &a){cout<< "show2:" <<a<<endl;}
};
int main()
{
show< int > a;
int temp1=5;
string temp2= "Hello,C++!" ;
a.show1(temp1);
a.show2(temp2);
return 0;
}
|
输出与上面一模一样,这里我就不把它粘上来了,^_^
|