c++/oop---函数模板

c++/oop---模板

函数模板

举例:swap

template <class c1,class c2 , ...>

返回值类型 模板名(形参表){

 

}

template<class T>

void swap (T & x, T & y){

       T tmp=x;x=y;y=tmp;

}

 

编译器在编译的时候回由模板自动生成函数,称作模板的实例化,得到的函数成为模板函数.

不通过参数实例化模板

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
template <class T>
T inc(int n){
	return 1+n;
}
int main()
{
	cout<<inc<double>(4)/2<<endl;
	return 0;
}

 

相当于指定 T 是 double ,这时一定需要指定。(否则不知道 T 是啥类型)

函数模板可以重载,只要它们的形参表或类型参数表不同即可。 

 

在有多个函数和函数模板名字相同的情况下,编译器如下处理一条函数
调用语句
1 先找参数完全匹配的普通函数(非由模板实例化而得的函数)。
2 再找参数完全匹配的模板函数。
3 再找实参数经过自动类型转换后能够匹配的普通函数

4 上面的都找不到,则报错。

 

参数不一定要是变量,甚至可以是函数

#include <iostream>
2 using namespace std;
3 template<class T,class Pred>
4 void Map(T s, T e, T x, Pred op) {
5 for(; s != e; ++s, ++x) {
6 *x = op(*s);
7 }
8 }
9 int Cube(int x) {
10 return x * x * x;
11 }
12 double Square(double x) {
13 return x * x;
14 }

int a[5] = {1,2,3,4,5}, b[5];
8 Map(a, a+5, b, Square); 
9 void Map(int * s, int * e, int * x, double ( *op)(double)) {
10 for(; s != e; ++s,++x) {
11 *x = op(*s);
12 }
13 }

 

template <class T1, class T2, class T3>
2 T1 func(T1 * a, T2 b, T3 c) { }
3 int a[10], b[10];
4 void f(int n) { }
func(a, b, f); 

将模板类型参数实例化的结果是:
A T1: int, T2: int *, T3: void (*) (int)

void (*) int 表示返回值为 void 参数表为 int 的一个函数指针

  

posted @ 2022-03-26 16:40  liankewei123456  阅读(74)  评论(0编辑  收藏  举报