69 模板(一)

图片
这里写图片描述

//max.h
#ifndef _MAX_H_
#define _MAX_H_

template <typename T>
const T& max(const T& a, const T& b)//必须将实现放在头文件
{
    return a < b ? b : a;
}

//函数模板重载
template <typename T>
const T& max(const T& a, const T& b,const T& c)//必须将实现放在头文件
{
    return ::max(a, b) < c ? c : ::max(a,b);
}

//非模板函数重载
const int& max(const int& a, const int& b)
{
    return a < b ? b : a;
}

template<>
const char* const& max(const char* const& a, const char* const& b)//函数模板特化
{
    return strcmp(a, b) < 0 ? b : a;//比较内容
}



#endif

//main.cpp
#include<iostream>
#include <string>
using namespace std;

#include "max.h"

//template<typename T>//模板。不是函数,不能被调用
//const T& max(const T& a, const T& b)
//{
//  return a < b ? b : a;
//}
int main(void)
{
    cout<<::max(5.5, 6.6)<<endl;//自动推导max(const int&, const int&)
    cout << ::max('a', 'c') << endl;

    const char* str1 = "aaa";
    const char* str2 = "zzz";
    cout << ::max(str1, str2) << endl;
    cout << ::max(1, 5, 3) << endl;

    cout << ::max<>(97, 100) << endl;//自动推导 max(const int&,const int&)
    cout << ::max<int>(97, 100) << endl;//显示指定模板函数 max(const int&,const int&)
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值