天天看点

函数重载和函数模板的对比

#include <iostream>
using namespace std;
//C++函数模版两种定义方式 
//template < typename T>  或  template <class T>
template <typename T1>
T1 check_max(T1 x, T1 y);
//C++重载
int check_max(int x, int y);

int main(void)
{
  int x = 33;
  int y = 44;
  long l1 = 333, l2 = 444;
  float f1 = 3.14, f2 = 3.15926;

  //系统会优先调用重载函数,而不是模板函数
  cout << "max(x, y) = " << check_max(x, y) << endl;
  //系统会自动识别类型 T1为long类型
  cout << "max(x, y) = " << check_max(l1, l2) << endl;
  //系统会自动识别类型 T1为float类型
  cout << "max(x, y) = " << check_max(f1, f2) << endl;
  cout << "==========================================" << endl;

  cin.get();
  return 0;
}

template <typename T1>
T1 check_max(T1 x, T1 y)
{
  cout << "调用模板函数打印" << endl;
  return x > y ? x : y;
}

int check_max(int x, int y)
{
  cout << "调用重载函数打印" << endl;
  return x > y ? x : y;
}      

继续阅读