欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c/c++ 函数模板初探

程序员文章站 2023-08-02 21:25:40
函数模板初探 1,由来:有时候,函数的逻辑是一样的,只是参数的类型不同,比如下面 2,解决办法,如果参数的类型也可以作为函数的参数,就可以解决了 3,函数模板写法:template\ 4,函数模板的效率不高,编译器在编译的时候,会根据调用测提供的参数去推导出T1等的类型,并给我们生成对应类型的方法。 ......

函数模板初探

1,由来:有时候,函数的逻辑是一样的,只是参数的类型不同,比如下面

int max(int a, int b){
  return a > b ? a : b;
}
double max(double a, double b){
  return a > b ? a : b;
}

2,解决办法,如果参数的类型也可以作为函数的参数,就可以解决了

t max(t a, t b){
  return a > b ? a : b;
}

3,函数模板写法:template<typename t1,typename t2, ...>

4,函数模板的效率不高,编译器在编译的时候,会根据调用测提供的参数去推导出t1等的类型,并给我们生成对应类型的方法。

5,下面的例子,调用的时候,可以明确给定参数的类型,max<int>(1, 2.1),这样一来,即使1和2.1的类型不同,编译也可以通过,如果只用max(1, 2.1),编译就不会通过,当然如果 max(t1 a, t2 b),也可以解决问题。

6,typeid(t).name() 返回t的类型的名字

#include <iostream>
#include <typeinfo>

using namespace std;

class test{
  friend ostream& operator<<(ostream &os, const test &t);
public:
  test(int d = 0) : data(d){}
  bool operator>(const test &t){
    return data > t.data ? true : false;
  }
  ~test(){}
private:
  int data;
};

ostream& operator<<(ostream &os, const test &t){
  os << "test::data : " << t.data;
  return os;
}
template<typename t>
t max(t a, t b){
  cout << typeid(t).name() << endl;
  return a > b ? a : b;
}

int main(){
  cout << max(1, 2) << endl;
  cout << max('a', 'b') << endl;
  cout << max(1.2f, 3.4f) << endl;
  cout << max(1.2, 3.4) << endl;

  test t(10);
  test t1(11);
  cout << max(t, t1) << endl;

  //编译不过,因为1和2.1的类型不同,但是模板函数的两个参数的类型是相同的,所以编译器不知道用哪种类型作为函数的参数了。
  //cout << max(1, 2.1) << endl;                                
  cout << max(1, (int)2.1) << endl;
  cout << max((double)1, 2.1) << endl;
  cout << max<int>(1, 2.1) << endl;
  cout << max<double>(1, 2.1) << endl;
  cout << max<>(1, 2) << endl;
}