C++模板(函数、类)

首先看看类模板

#include <iostream> // using cout and endl
#include <fstream> // using operate file
#include <cmath> // using sqrt
#include <ctime> // using time
#include <cstdlib> // using rand
#include <iomanip> // using setw
#include <vector> // using vector
#include <cstring> // using strlen
#include <exception> // using standard exception
#include <stdexcept> // using out_of_range func
using namespace std;

template <class T>
class my_class{
      public:
            vector<T> element;
            void push(T const& ele){
                  element.push_back(ele); // 入栈
            }
            void pop();
            T top() const;
            bool empty() const{
                  return element.empty(); // 栈为空
            }
};
template <typename T>
void my_class<T>::pop(){
      if(element.empty()){
            throw out_of_range("out of range"); // 判断栈元素越界
      }
      element.pop_back(); // 出栈
}
template <typename T>
T my_class<T>::top()const{
      if(element.empty()){
            throw out_of_range("out of range"); // 抛出异常
      }
      return element.back(); // 栈顶元素
}
int main(){
      try{
      my_class<int> int_class;
      int_class.push(7);
      cout << int_class.top() << endl;
      int_class.pop();
      cout << int_class.top() << endl;
      }catch(exception const & e){
            cout << e.what() << endl;
      }
      return 0;
}
函数模板

#include <iostream>
using namespace std;

template <typename T>

inline T const & Max(T const & a, T const & b){
      return a>b?a:b;
}

int main(){
      int a1=9, b1 = 10;
      double a2=18, b2=90;
      cout << Max(a1, b1) << endl;
      cout << Max(a2, b2) << endl;
      return 0;
}

template <typename T>  可以修改成   template <class T>

模板实际上就是脱离类型。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值