環(huán)境:ide:Mac+clion
視頻鏈接:
https://www.bilibili.com/video/BV1Hb411Y7E5?p=5
c++范型編程,利用模版技術(shù):函數(shù)模版和類模版
T 通用類型,虛擬類型。
自動類型推導(dǎo),一致的數(shù)據(jù)類型才可以使用。
函數(shù)聲明和定義。typename 可以用class 替換。
//template<typename T>//typename 可以用class 替換
template<class T>
void sheikSwap(T &a,T &b){//自動類型推導(dǎo),一致的數(shù)據(jù)類型才可以使用。
T temp;
temp = a;
a = b;
b = temp;
}
void test(){
int a = 10;
int b = 20;
cout << "swap 前:"<<a <<","<<b<<endl;//10 20
sheikSwap(a,b);
cout << "swap 后:"<<a <<","<<b<<endl;//20 10
}
1.普通函數(shù)和模版函數(shù)重載,優(yōu)先調(diào)用普通函數(shù)。
2.如果強(qiáng)制調(diào)用重載模版類,用空模版空參數(shù)列表<>來調(diào)用。
void myPrint(string a){
cout << "普通函數(shù)打印調(diào)用"<<endl;
}
template<class T>
void myPrint(T a){
cout << "范型函數(shù)打印調(diào)用"<<endl;
}
int main()
{
//test();
string a = "";
myPrint(a);//普通函數(shù)打印調(diào)用
myPrint<string>(a);//范型函數(shù)打印調(diào)用,顯示制定類型
myPrint<>(a);//范型函數(shù)打印調(diào)用,隱士調(diào)用。
return 0;
}
模版的局限性
針對自定義的對象進(jìn)行判等 等操作,可以通過重載==進(jìn)行解決。
class Person{
public:
string m_Name;
int m_Age;
};
template<class T>
bool myCompare(T &a, T &b) {
cout << "myCompare 模版 "<<endl;
if (a == b) {
return true;
}
return false;
}
template<> bool myCompare(Person &p1,Person &p2){
cout << "myCompare 重新實(shí)現(xiàn)"<<endl;
if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age){
return true;
}
return false;
}
void test() {
Person p1 ;
p1.m_Name = "sheik";
p1.m_Age = 10;
Person p2 ;
p2.m_Name = "sheik";
p2.m_Age = 10;
cout << myCompare(p1,p2)<<endl;//輸出的是1
};
類模版 與 函數(shù)模版的區(qū)別
類模版沒有自動推導(dǎo)功能,只能顯示調(diào)用。
template<class NameType,class AgeType = int>//類模版,這里可以進(jìn)行確定類型。也可以不進(jìn)行確定。類模版獨(dú)有。
//template<class NameType,class AgeType>//類模版
class Person{
public:
Person(NameType name,AgeType age){
this->m_Name = name;
this->m_Age = age;
}
NameType m_Name;
AgeType m_Age;
};
void test(){
Person<string,int> person("sheik",20);
cout << person.m_Name << ","<<person.m_Age<<endl;
}
類的成員函數(shù),類創(chuàng)建的時候,就創(chuàng)建出來了。模版函數(shù)是函數(shù)調(diào)用的時候才創(chuàng)建出來。
class Person1 {
public:
void showPerson1() {
cout << "showPerson1 call" << endl;
}
};
template<class T>
class Person {
public:
T t;
Person(T t):t(t){
}
void showPerson() {
t.showPerson1();//這里可以編譯通過,只能說是在調(diào)用的時候創(chuàng)建。
}
void showInfo() {
cout << "模版類的showInfo()進(jìn)行調(diào)用!" << endl;
};
};
void test(Person<Person1> &person) {
person.showPerson();
person.showInfo();
}
int main() {
Person1 person1;
Person<Person1>person(person1);
test(person);
return 0;
}
通過參數(shù)模版化進(jìn)行傳遞,當(dāng)參數(shù)通過范型來傳遞的時候,可以通過typeid(T).name 來查看T的類型。
template<class T>
void test(Person<T> &p){
p.showInfo();
cout << typeid(T).name()<<endl;
}
整個類進(jìn)行模版化
template<class T>
void test1(T &p){//這里把整個Person 類進(jìn)行模版
p.showInfo();
cout << typeid(T).name()<<endl;
}