[C++]template 模板函数

[C++]template 模板函数,第1张

一个模板函数的小例子

  1. 需求实现一个比较大小的模板函数

  2. 代码实现:

#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;
}
  1. 运行结果

template compare
a:7, b:8
template compare
a:7, b:8
template compare
a:7.7, b:8.8

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/867091.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-12
下一篇2022-05-12

发表评论

登录后才能评论

评论列表(0条)

    保存