C++ 比較大小函數(shù)模板

#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;
}

當(dāng)兩個(gè)參數(shù)類型不一致在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 可以當(dāng)做int類型變量使用
}
int main() {
    cout << fun<double,int,5>(3.0, 5, 6);
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,544評(píng)論 19 139
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,901評(píng)論 0 33
  • 國(guó)家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說(shuō)閱讀 12,359評(píng)論 6 13
  • 86.復(fù)合 Cases 共享相同代碼塊的多個(gè)switch 分支 分支可以合并, 寫在分支后用逗號(hào)分開(kāi)。如果任何模式...
    無(wú)灃閱讀 1,552評(píng)論 1 5
  • 倘若我能以達(dá)到 上帝 何處是你心的盡頭 可能容我知道 遠(yuǎn)了 十分的遠(yuǎn)了 我真是太微小
    夢(mèng)雙眸閱讀 379評(píng)論 5 12

友情鏈接更多精彩內(nèi)容