类模板也是可以实例化对象的,因此类模板也可以做函数参数。
1、作用
类模板实例化出的对象,向函数传参的方式。
2、一共有三种传入方式:
- 指定传入的类型:直接显示对象的数据类型
- 参数模板化:将对象中的参数变为模板进行传递
- 整个类模板化:将这个对象类型模板化进行传递
指定传入的类型
直接举个例子
#include<iostream>
#include<string>
using namespace std;
void test01();//函数的声明
int main()
{
test01();
system("pause");
return 0;
}
//类模板对象做函数参数
template<class T1, class T2>//创建一个类模板
class person
{
public:
T1 m_name;
T2 m_age;
person(T1 name, T2 age)//指定参数
{
this->m_name = name;
this->m_age = age;
}
void showPerson()
{
cout << "name:" << this->m_name << endl;
cout << "age: " << this->m_age << endl;
}
};
void printPerson(person<string , int>&p)//将整个类模板作为参数传递进函数
{
p.showPerson();//调用
}
void test01()
{
person<string, int > p("孙悟空", 999);
printPerson(p);//传参
}
参数模板化
直接举个例子
#include<iostream>
#include<string>
using namespace std;
void test02();
int main()
{
test02();
system("pause");
return 0;
}
//类模板对象做函数参数
template<class T1, class T2>
class person
{
public:
T1 m_name;
T2 m_age;
person(T1 name, T2 age)
{
this->m_name = name;
this->m_age = age;
}
void showPerson()
{
cout << "name:" << this->m_name << endl;
cout << "age: " << this->m_age << endl;
}
};
/*以上的类的构建就不细说了*/
template <class T1, class T2>//将模板声明,否则下一句话将报错,编译器没办法识别T
void printPerson2(person<T1, T2>&p)//直接将参数模板化,不细分是int还是string,一律模板化为T。
{
p.showPerson();
cout << "T1的类型为: " << typeid(T1).name() << endl;
cout << "T2的类型为: " << typeid(T2).name() << endl;
}
void test02()
{
person <string, int >p("猪八戒", 90);
printPerson2(p);
}
最后的结果是:
name:猪八戒
age: 90
T1的类型为: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
T2的类型为: int
请按任意键继续. . .
可以看书,T1和T2的类型。
整个类模板化
直接上例子:
#include<iostream>
#include<string>
using namespace std;
void test03();
int main()
{
test03();
system("pause");
return 0;
}
//类模板对象做函数参数
template<class T1, class T2>
class person
{
public:
T1 m_name;
T2 m_age;
person(T1 name, T2 age)
{
this->m_name = name;
this->m_age = age;
}
void showPerson()
{
cout << "name:" << this->m_name << endl;
cout << "age: " << this->m_age << endl;
}
};
template<class T>//直接将整个类模板化,传递的参数只整个的一个类模板
void printPerson3(T &p)
{
cout << "T的类型为: " << typeid(T).name() << endl;
p.showPerson();
}
void test03()
{
person <string, int >p("唐僧", 30);
printPerson3(p);
}
最后的结果是
T的类型为: class person<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int>
name:唐僧
age: 30
请按任意键继续. . .
总结:
- 通过类模板创建的对象,可以有三种方式向函数中进行传参
- 使用比较广泛是第一种:指定传入的类型