函数模板
#include<bits/stdc++.h>
using namespace std;
/**
* 函数模板
* */
template<class T>
void my_swap(T &a, T &b) {
T temp;
temp = a;
a = b;
b = temp;
}
int main() {
int a = 1, b = 2;
my_swap(a, b);
printf("a=%d b=%d\n", a, b);
double c = 1.535, d = 2.55;
my_swap(c, d);
printf("c=%.2f d=%.2f\n", c, d);
return 0;
}
类模板
#include<bits/stdc++.h>
using namespace std;
/**
* 类模板
* */
template<class T>
class Trray {
public:
Trray(int siz = 1) {
this->siz = siz;
aptr = new T[siz];
}
void fill_array();
void dis_array();
~Trray() {
delete []aptr;
}
private:
int siz;
T *aptr;
};
template<class T>
void Trray<T>::fill_array() {
printf("please input %d data\n", siz);
for(int i = 0; i < siz; i++) {
printf("the %d data", i+1);
cin>>aptr[i];
}
}
template<class T>
void Trray<T>::dis_array() {
for(int i = 0; i < siz; i++) {
cout<<aptr[i]<<" ";
}
cout<<endl;
}
int main() {
Trray<char> ac(3);
ac.fill_array();
ac.dis_array();
Trray<float>af(3);
af.fill_array();
af.dis_array();
return 0;
}
类模板派生
#include<bits/stdc++.h>
using namespace std;
/**
* 类模板派生
* */
template<class T>
class A {
public:
void showA(T a) {
cout<<a<<endl;
}
};
template<class X, class Y>
class B: public A<Y> {
public:
void showB(X b) {
cout<<b<<endl;
}
};
int main() {
B<char, int> b;
b.showA(10);
b.showB('c');
return 0;
}