C++泛型编程:类模板(下)
类模板与继承:
需要指定模板参数的类型
template <class T>
class Base
{
public:
T m;
};
class Son :public Base<int>
{
};
template <typename T1,typename T2>
class Son2 :public Base<T2>
{
public:
Son2()
{
cout << "T1的类型:" << typeid(T1).name() << endl;
cout << "T2的类型:" << typeid(T2).name() << endl;
}
T1 obj;
};
void test01()
{
Son2<int, char> S2;
}
类模板分文件编写:
方法1:(主流)
将声明与实现放在同一个文件中,可将该文件的后缀名由 “.h" 改为 ".hpp" 。并非强制,而是方便其他用户阅读源文件。
方法2:
头文件 "person.h":
#pragma once
#include<iostream>
#include<string>
using namespace std;
template <class T1,class T2>
class Person
{
public:
Person(T1 name, T2 age);
void showPerson();
T1 m_Name;
T2 m_Age;
};
源文件 "person.cpp":
#include"person.h"
template <class T1,class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
template <class T1, class T2>
void Person<T1, T2>::showPerson()
{
cout << this->m_Name << " " << this->m_Age << endl;
}
在主函数中包含源文件,(原因:模板的函数在调用时才会创建)这样使得编译器可以看到函数的具体实现。
#include<iostream>
using namespace std;
#include"person.cpp"
void test02()
{
Person<string, int> p1("Zhang", 19);
p1.showPerson();
}
int main()
{
test02();
system("pause");
return 0;
}
类模板与友元:
全局函数类内实现:
直接在类内声明友元即可
template <class T1, class T2>
class Person
{
friend void printPerson(Person<T1, T2> p)
{
cout << p.m_Name << " " << p.m_Age << endl;
}
public:
Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
T1 m_Name;
T2 m_Age;
};
全局函数类外实现:
需要让编译器提前知道函数的存在
同时类内的函数声明需要加空模板参数列表
template<typename T1, typename T2>
class Person;
template<typename T1, typename T2>
void printPerson2(Person<T1, T2> p)
{
cout << "Name:" << p.m_Name << " Age:" << p.m_Age << endl;
}
template <class T1, class T2>
class Person
{
//需要加空模板参数列表
friend void printPerson2<>(Person<T1, T2> p);
public:
Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
T1 m_Name;
T2 m_Age;
};
void test03()
{
Person<string, int> p("Tom", 19);
printPerson(p);
printPerson2(p);
}
建议:没有特殊需求的话,全局函数做类内实现,用法简单而且编译器可以直接识别