函数模板,打印数组。
用关键字typename 指出函数模板形参 ,实际上就是指任何内置类型。
template
- // Fig14_01_printArray.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
- //
-
- #include <iostream>
- using namespace std;
-
- //function template printArray definition
- template <typename T>
- void printArray(const T* const array, int count)
- {
- for (int i = 0; i < count; i++)
- cout << array[i] << " ";
- cout << endl;
- }//end function template printArray
-
-
- int main()
- {
- const int aCount = 5;// size of array a
- const int bCount = 7;// size of array b
- const int cCount = 6;// size of array c
-
- int a[aCount] = {1,2,3,4,5};
- double b[bCount] = { 1.1,2.2,3.3,4.4,5.5,6.6,7.7 };
- char c[cCount] = { "Hello" };//6th position for null
- cout << "Array a contains:" << endl;
-
- //call integer function-template specialization
- printArray(a,aCount);
-
- // double function-template specialization
- cout << "Array b contains:" << endl;
- printArray(b,bCount);
-
- //char function-template specialization
- cout << "Array c contains:" << endl;
- printArray(c,cCount);
- }
-
-
运行结果:
- Array a contains:
- 1 2 3 4 5
- Array b contains:
- 1.1 2.2 3.3 4.4 5.5 6.6 7.7
- Array c contains:
- H e l l o