c++中的template类是一种很高端的用法。它是一种模板,有类模板、函数模板等。
一、类模板
想实现swap函数,但又不会实现对任意类的交换,怎么办?
template大法!
template <typename T>
void myswap(T &__a,T&__b){
T __c;
__c=__a;
__a=__b;
__b=__c;
}
解释一下:
1.typename
typename是用来规定后面的T是类型名,而非变量名。如果是两个double类型交换,那么T就为double,如果是两个结构体交换,那么T就是结构体名。
2.取地址符 ‘&’
对于要交换的两个数__a和__b,如果不加’&’,就只是在myswap函数里面交换,而对数本身没有影响。’&'实质上是一种指针,指向要交换的两个数。
例:
scanf("%d %d",&a,&b);
如果在较为复杂的程序里面不加’&’,就会编译错误或结果错误。
3. ___a与___b
为什么要用__a和__b呢?
在写头文件的过程中,如果不这样写,有时就会导致编译错误,即:头文件中的变量与程序之间的变量重复。
二、模板函数
对于以下程序片段:
template <class S>
class A{
private:
S __d;
int __e;
public:
S plus(S __a,S __b);
A();
};
你既可以将它写成一个头文件,也可以直接写在程序中。
class与typename相似。
引用时需这样:\text{引用时需这样:}引用时需这样:
#include<bits/stdc++.h>
#include "templatetry.h"
using namespace std;
template <class S> A<S>::A() {}
template <class S> S A<S>::plus(S __a,S __b) {
return __a+__b;
}
int a,b;
int main(){
cin>>a>>b;
myswap(a,b);
A<int> c;
cout<<a<<' '<<b<<endl;
cout<<c.plus(a,b);
return 0;
}