模板在c++中很有帮助 合理运用模板可以节约工作量啦
附上简单的模板代码
#include<iostream>
using namespace std;
template<class T1, class T2>
auto add(T1 t1, T2 t2)
{
return t1 + t2;
}
int main(void)
{
cout << add(1.2, 2) << endl;
cout << add(2, 2.2) << endl;
cout << add('a', 'b') << endl;
cin.get();
return 0;
}
省时省力 岂不美滋滋?
下面有一个现象 就是关于模板别名的使用 C++里面使用模板的别名用using = 就可以了 用typedef反而会报错
#include<iostream>
using namespace std;
template<class T> using t1 = T;
template<class T>using t2 = T*;
template<class T>
T show(T a)
{
t1<int> temp(a);
t2<int> add(&a);
cout << temp <<" "<< add << endl;
return temp;
}
int main(void)
{
cout << show(5) << endl;
cin.get();
return 0;
}
这里需要指出的一点就是 用别名的时候必须要制定类型
t1<int> temp(a);
t2<int> add(&a);
不指定类型会报错 另外注意啊 本文所指的所有标准都是在c++14的标准下的 c++11会要求有一个具体的指向 具体可以百度 本文不再赘述
那么用其本名反而不需要制定类型
T temp(a);
T* add(&a);
这样就可以啦
所以个人觉得对于大型的开发而言 还是换成有实际意义的名称比较好 另外制定类型也能帮助我们来判断写的是否正确,不是吗?
同时附上c++风格的数组别名~~~
买一送多 很划来哦
using intarray = array<int, 10>;
intarray myarray1;
要注意这一个必须要包括头文件#include<array>