C++ 比较大小函数模板

#include <iostream>
#include <stdlib.h>

template<typename T>
T max(T a, T b) {
    return (((a) > (b)) ? (a) : (b));
}

int main()
{
    // This will call max<int> by implicit argument deduction.
    std::cout << max(3, 7) << std::endl;

    // This will call max<double> by implicit argument deduction.
    std::cout << max(3.0, 7.0) << std::endl;

    // This depends on the compiler. Some compilers handle this by defining a template
    // function like double max <double> ( double a, double b);, while in some compilers 
    // we need to explicitly cast it, like std::cout << max<double>(3,7.0);
    //std::cout << max(3, 7.0) << std::endl;
    std::cout << max<double>(3, 7.1) << std::endl;
    return 0;
}

当两个参数类型不一致在vs中
max<double>(3,7.1)
output:7.1

#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T1,typename T2 ,int NUM> double fun(T1 a,int b,T2 c)
{
    int number = 0;
    return a*(number + b)*c; // number 可以当做int类型变量使用
}
int main() {
    cout << fun<double,int,5>(3.0, 5, 6);
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,948评论 18 139
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,166评论 6 13
  • 86.复合 Cases 共享相同代码块的多个switch 分支 分支可以合并, 写在分支后用逗号分开。如果任何模式...
    无沣阅读 1,433评论 1 5
  • 倘若我能以达到 上帝 何处是你心的尽头 可能容我知道 远了 十分的远了 我真是太微小
    梦双眸阅读 362评论 5 12