相关内容:
- 所谓函数模板,实际上是建立一个通用函数,它所用到的数据的类型(包括返回值类型、形参类型、局部变量类型)可以不具体指定,而是用一个虚拟的类型来代替(实际上是用一个标识符来占位),等发生函数调用时再根据传入的实参来逆推出真正的类型。这个通用函数就称为函数模板(
Function Template
)。 - 在函数模板中,数据的值和类型都被参数化了,发生函数调用时编译器会根据传入的实参来推演形参的值和类型。换个角度说,函数模板除了支持值的参数化,还支持类型的参数化。
- 一但定义了函数模板,就可以将类型参数用于函数定义和函数声明了。说得直白一点,原来使用
int
、float
、char
等内置类型的地方,都可以用类型参数来代替。
模板函数定义的一般形式如下所示:1
2
3
4template <class T> // or template <typename T>
returnType functionName ( params ) {
// todo something
}template
是定义函数模板的关键字,它后面紧跟尖括号<>
,尖括号包围的是类型参数(也可以说是虚拟的类型,或者说是类型占位符)。每一个类型参数T
之前都有关键字class
或者关键字typename
,这些类型参数代表的是类型,可以是内部类型或自定义类型。typename
是另外一个关键字,用来声明具体的类型参数,这里的类型参数就是T
。从整体上看,template
被称为模板头。代码相关内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using namespace std;
//int compare(const double &v1, const double &v2)
//{
// if (v1 < v2) return -1;
// if (v1 > v2) return 1;
// return 0;
//}
//
//int compare(const string &v1, const string &v2)
//{
// if (v1 < v2) return -1;
// if (v1 > v2) return 1;
// return 0;
//}
template <typename T> // typename也可以写class; T也可以用其他代替,比如用Object代替T,但是下面的T都要换成Object;
int compare(const T &v1, const T &v2)
{
if (v1 < v2) return -1;
if (v1 > v2) return 1;
return 0;
}
template <class T>
T absVal(T val) // 由此可知函数的返回值类型和传入的参数类型一致;可以实现求绝对值的功能;
{
return val > 0 ? val : -val;
}
template<typename T1, typename T2>
T1& print(T1& s, T2 val) // 可以通过选择将val输出到s中,s可以是文件流,也可以是字符串流;
{
s << val;
return s;
}
template <class T>
const T& bigger(const T& v1, const T& v2) //返回两者中的大数;注意此处因为传入类型为const,且返回的是v1或者v2中的一个,所以返回值类型应该加上const;
{
return v1 > v2 ? v1 : v2;
}
int main()
{
double dval = -0.88;
float fval = -12.3;
string oristr = "this is a test.";
string desstr;
ostringstream oss(desstr);
ofstream outFile("result.dat");
print(cout, -3) << endl;//此时T2为int;
print(cout, dval) << endl;//此时T2为double;
print(cout, fval) << endl;//此时T2为float;
print(cout, oristr) << endl;//此时T2为字符串流;
cout << endl;
//输出到文件
print(outFile, -3) << endl;
print(outFile, dval) << endl;
print(outFile, fval) << endl;
print(outFile, oristr) << endl;
outFile.close();// 关闭文件;
//输出到字符串流
print(oss, -3) << endl;
print(oss, dval) << endl;
print(oss, fval) << endl;
print(oss, oristr) << endl;
cout << oss.str() << endl; //将oss进行输出;
cout << absVal(dval) << endl;
cout << absVal(fval) << endl;
double d1 = 1.11;
double d2 = 9.56;
cout << compare(d1, d2) << endl;//此处c++会自动从函数模板实例化出对应的类型;此处实例化出double类型的函数;
string s1("hihihi");
string s2("world");
cout << compare(s1, s2) << endl;//此处c++会自动从函数模板实例化出对应的类型;此处实例化出string类型的函数;
cout << endl;
double a = 1.23;
double b = 5.89;
cout << bigger(a, b) << endl;
cout << bigger(s1, s2) << endl;
return 0;
}代码执行结果:
参考链接:
C++函数模板(Function Template)
C++ 函数模板与类模板