![[C++]template 模板函数,第1张 [C++]template 模板函数,第1张](/aiimages/%5BC%2B%2B%5Dtemplate+%E6%A8%A1%E6%9D%BF%E5%87%BD%E6%95%B0.png)
一个模板函数的小例子
-
需求实现一个比较大小的模板函数
-
代码实现:
#include
#include
template<class T>
bool compare(T a, T b){
std::cout << "template compare" <<std::endl;
std::cout << "a:" << a << ", b:"<< b<<std::endl;
return a > b;
}
int main(){
compare<int>(7, 8); //在函数调用点,编译器用用户指定的类型,从原模板实例化一份函数代码出来
compare<int>(7.7, 8.8);
compare(7.7, 8.8);
return 0;
}
- 运行结果
template compare
a:7, b:8
template compare
a:7, b:8
template compare
a:7.7, b:8.8
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)