#include <iostream>
#include <string>
using namespace std;
//函数模板,typename 等价于 class
template <typename AnyType>
void test(AnyType &a, AnyType &b) {
auto c = a;
a = b;
b = c;
}
//重载模板
template <typename AnyType>
void test(AnyType &a,AnyType &b,AnyType &c) {
c = a+b;
}
template <typename T>
void test(T *a,T *b,T *c) { //传指针地址的实参方式,在析构函数时,c值的改变也对应改变外部参数
*c = *a+*b;
}
template <typename T> //c 是新创建的int变量,和外部参数值互不影响 , ab是两种引用的表现方式
void test(T *a,T &b, int c) {
auto to = *a;
*a = b;
b = to;
c++;
}
template <typename AnyType2>
void test2(AnyType2 &a, AnyType2 &b) {
auto c = b;
b = a;
a = c;
}
template <class T>
void test3(T &a, T &b) {
auto c = a;
a = b;
b = c;
}
struct stdo {
float fu;
char cr[30];
};
//具体化显式模板
template <typename T>
void testss(stdo &a ,stdo &b){
auto fu = a.fu;
a.fu = b.fu;
b.fu = fu;
}
template <int>
void ttsdf(int i,int b){
cout << "f" << endl;
}
int main(int argc, const char * argv[]) {
//概念:C++编译器实现了新增一项特性--函数模板,通用的函数描述;使用泛型定义函数
int i = 10;
int ii = 200;
int iii = 100;
string a = "aaa";
string b = "bbbb";
size_t tt = a.length();
//利用泛型的函数模板交换两个整型值
test(i,ii);
cout << "交换两个整型值\n" << "i=" << i << endl << "ii=" << ii << endl;
test(&i, &ii, &iii);
cout << "重载\n" << "iii=" << iii << endl << "=" << ii << endl;
test(&i, ii, iii);
cout << "重载\n" << "iii=" << iii << endl << "i=" << i << endl << "ii=" << ii << endl;
//利用泛型的函数模板交换两个字符串值
test2(a,b);
cout << "交换两个字符串值\n" << "a=" << a << endl << "b=" << b << endl;
//显式模板,交换两个结构体中的元素
cout.precision(2); //保留小数点后两位
cout.setf(ios::fixed, ios::floatfield);
stdo sto = {999.234,"dsfsdf"};
stdo sto2 = {110.45222,"aaaaaa"};
testss<stdo>(sto,sto2);
cout << "显式模板\n" << "sto.fu=" << sto.fu << endl << "sto2.fu=" << sto2.fu << endl;
ttsdf<2>(10, 10);
return 0;
}