C++模板

本文深入探讨了函数模板和类模板的使用,展示了如何通过模板实现泛型编程,包括模板函数的重载、模板参数的使用及模板类的实例化。

模板的声明和实现必须放在一起编译

函数模板

函数模板可以重载,由函数模板产生的函数称为模板函数

#include <iostream>
using namespace std;
template <class T1,class T2>
T1 max(T1 a,T2 b){
    return a>b?a:b;
}
template <class T,int size>
void show(){
    if(size<0)
        cout<<"-1";
    else
        cout<<size<<endl;
}
int main(){
    cout<<max<int,int>(1,2)<<endl;
    cout<<max(1,2.2)<<endl;
    cout<<max(2.2,1)<<endl;
    show<int,5>();
}

类模板

由类模板产生的类称为模板类

#include <iostream>
using namespace std;
template <typename T>
class Node{
    T x = 0;
    T y = 0;
public:
    void show();
    void display(){
        cout<<x<<" "<<y<<endl;
    }
};
template<typename T>//according to this format
void Node<T>::show(){
    cout<<x<<" "<<y<<endl;
}
int main(){
    Node<int> node;
    node.show();
    node.display();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值