C++ 使用模板需要注意的事情
总结:
●使用模板时必须确定出通用数据类型T,并且能够推争出一致的类型
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
//函数模板注意事项
template<class T> //typename 可以替换成class
void mySwap(T&a, T&b){
T temp = a;
a = b;
b = temp;
}
//1、自动类型推导,必须推导出- -致的数据类型T才可以使用
void test01() {
int a = 10;
int b = 20;
char c = 'c';
mySwap(a,b); //正确!
//mySwap(a, c); //错误!
mySwap(a,b); //正确!
cout << "a=" << a <<endl;
cout << "b=" << b <<endl;
}
//2、模板必须要确定出T的数据类型,才可以使用
template<class T>
void func() {
cout << "func调用" << endl;
}
void test02(){
func<int>();
}
int main() {
test01();
system("pause");
return 0;
}
还没有评论,来说两句吧...