C++之函数模板
2017-09-15 15:58
218 查看
其实关于函数模板自己已经看了很多次了,只是实在太菜,用的很少以至于总是给忘了,现在简单记下来。
函数模板是通用的函数描述,其通过将类型作为参数传递给模板,可使编译器生成该类型的函数。
一个简单的函数模板例程:
需要多个对不同类型使用同一种算法的函数时,可以通过类似上面程序的模板。但并非所有的类型都使用相同的算法,这时就可以像重载常规函数定义一样重载模板定义。和常规重载一样,被重载的模板的函数特征标必须不同。
【参考】:C++ Primer Plus
函数模板是通用的函数描述,其通过将类型作为参数传递给模板,可使编译器生成该类型的函数。
一个简单的函数模板例程:
#include <iostream> using namespace std; template <typename T> void Swap(T &a, T &b); int main() { int i = 10; int j = 20; cout << "i, j = " << i << ", " << j << endl; Swap(i, j); cout << "Now i, j = " << i << ", " << j << endl; double x = 24.5; double y = 87.1; cout << "x, y = " << x << ", " << y << endl; Swap(x, y); cout << "Now x, y = " << x << ", " << y << endl; return 0; } template <typename T> void Swap(T &a, T &b) { T temp; temp = a; a = b; b = temp; }
需要多个对不同类型使用同一种算法的函数时,可以通过类似上面程序的模板。但并非所有的类型都使用相同的算法,这时就可以像重载常规函数定义一样重载模板定义。和常规重载一样,被重载的模板的函数特征标必须不同。
#include <iostream> template <typename T> void Swap(T &a, T &b); template <typename T> void Swap(T *a, T *b, int n); void Show(int a[]); const int Lim = 8; int main() { using namespace std; int i = 10, j = 20; cout << "i, j = " << i << ", " << j << endl; cout << "Using complier-generated int swapper: \n"; Swap(i, j); cout << "Now i, j = " << i << ", " << j << endl; int d1[Lim] = {0, 7, 0, 4, 1, 7, 7, 6}; int d2[Lim] = {0, 7, 2, 0, 1, 9, 6, 9}; cout << "Original arrays:\n"; Show(d1); Show(d2); Swap(d1, d2, Lim); cout << "Swapped arrays: \n"; Show(d1); Show(d2); return 0; } template <typename T> void Swap(T &a, T &b) { T temp; temp = a; a = b; b = temp; } template <typename T> void Swap(T *a, T *b, int n) { T temp; for (int i = 0; i < n; i++) { temp = a[i]; a[i] = b[i]; b[i] = temp; } } void Show(int a[]) { using namespace std; cout << a[0] << a[1] << "/"; cout << a[2] << a[3] << "/"; for (int i = 4; i < Lim; i++) { cout << a[i]; } cout << endl; }
【参考】:C++ Primer Plus
相关文章推荐
- c++ 模板学习笔记:函数模板实现数组通用排序和遍历打印(权哥)
- C++学习笔记_7:函数模板
- 读书笔记 effective c++ Item 45 使用成员函数模板来接受“所有兼容类型”
- C++ 函数模板
- C++模板:函数模板和模板函数详解
- c++ 函数模板
- 基于c++的函数模板
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- C++:函数模板
- 利用C++模板,代替虚函数,实现类的静态多态性(加入性能测试部分)
- C++在类内定义模板函数
- c++入门学习(函数模板)
- C++ 函数模板 实例化和具体化
- c++ 模板之函数模板
- c++:函数模板与函数包装器
- C++模板:函数模板和模板函数
- C++ 函数、函数模板、类模板、函数列表
- C++进阶之函数模板
- C++ 函数模板和排序的函数模板——学习笔记
- C++模板的定制一:定制函数模板