C++ template

参考链接:1.cplusplus

c++ 的template(模板)分为function templates和class templates,模板是能够操作通用类型的一种方法,它能用同样的代码自适应多种类型实现同样的功能,从而实现代码重用。而这是通过使用模板参数 实现的,即将类型也当作参数

  • 函数模板声明:
  /***两种使用方式没有区别***/
  template <class identifier> function_declaration
  template <typename identifier> fucntion_declaration
  • 函数模板例子:
  #include <iostream>
  using namespace std;

  //OR: template <typename T> T getMax(T a, T b){...}
  template <class T>
  T getMax(T a, T b){
    return (a > b) ? a : b;
  }

  int main(){
    cout << getMax<int>(5, 6) << endl;
    system("pause");
    return 0;
  }
  • 类模板语法:
  // 定义
  template <class T>
  class MyClass{
    T par;
  public:
    T my_func();
    int our_func();
  }
  // 成员函数定义
  template <class T>  //都要有template <class T> 开头
  int MyClass<T>::our_func(){...} //这里不要忘记类后面的<T>

  • 类模板例子:

    
    #include <iostream>
    
    using namespace std;
    
    template <typename T>
    class MyPair{
    T a, b;
    public:
    MyPair(T _a, T _b){
        a = _a;
        b = _b;
    }
    T get_max();
    };
    
    template <typename T>
    T MyPair<T>::get_max(){
    return a > b ? a : b;
    }
    
    int main(){
    MyPair<int> age(21, 23);
    cout << age.get_max() << endl;
    system("pause");
    return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值