// 模板有两种:函数模板(typename)类模板(class)
// 定义函数模板
// template <typename T>
// 定义类模板
// template<class T>
// 无论是typename还是class都是模板
// 使用模板的注意事项
// 1.自动类型推导的数据类型必须一样
// 比如:
template <typename T>
void Swap(T &a,T &b)
{
T temp;
temp=a;
a=b;
b=temp;
}
void test1()
{
int a=10;
int b=20;
Swap(a,b);
// 正确,传入的数据类型一致
int c=34;
char b='a';
Swap(c,b);
// 错误,传入的数据类型不同,编译器无法自动推导出正确的数据类型(到底是int,还是char)
}
// 2.有必要指定函数模板的数据类型,最好还是要指定数据类型
template <typename T>
void fun()
{
cout<<"This is a template function"<<endl;
}
void test2()
{
// 指定模板函数的数据类型
fun<int>();
}
C++函数模板的注意事项
最新推荐文章于 2024-01-05 15:33:51 发布