再來說樣板template,樣板只有參數型態不一樣其餘都相同(包括程式邏輯),樣板基本上與寫一般的函式沒甚麼差別,但變數型態並不指定而是通常由一個名為正規型別引數(Formal type parameter)的T取代如下螞蟻書範例:
T maximum( T value1, T value2, T value3 ){
T maximumValue = value1; // assume value1 is maximum
// determine whether value2 is greater than maximumValue
if ( value2 > maximumValue )
maximumValue = value2;
// determine whether value3 is greater than maximumValue
if ( value3 > maximumValue )
maximumValue = value3;
return maximumValue;
} // end function template maximum
程式邏輯非常簡單傳進來三個value,首先將maximumValue設為value1再讓value2與maximumValue比大小如果value2大於maximumValue則將maximumValue設為value2,接著對value3重覆相同邏輯,跟一般函式的差別只有型態用T代替,當然這樣去run編譯器會直接報錯因為從頭到尾沒講T是啥? 所以開頭要補這一段template < class T >或是 template< typename T >完整程式碼如下在main()函數中要比哪種型態都可以,不知諸位是不是充分體驗到C++的樂趣呢?那麼簡單的語言被CS101換掉當然是有原因的,C++還有更風騷的操作overloading + template + static,砸再一起做撒尿牛丸一整個花枝招斬,那麼好的語言絕對不能只有我學過!喔對了還有一個泛型(generic)沒說。
// Fig. 6.26: maximum.h
// Definition of function template maximum.
template < class T > // or template< typename T >
T maximum( T value1, T value2, T value3 ){
T maximumValue = value1; // assume value1 is maximum
// determine whether value2 is greater than maximumValue
if ( value2 > maximumValue )
maximumValue = value2;
// determine whether value3 is greater than maximumValue
if ( value3 > maximumValue )
maximumValue = value3;
return maximumValue;
} // end function template maximum
// Fig. 6.27: fig06_27.cpp
// Function template maximum test program.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "maximum.h" // include definition of function template maximum
int main()
{
// demonstrate maximum with int values
int int1, int2, int3;
cout << "Input three integer values: ";
cin >> int1 >> int2 >> int3;
// invoke int version of maximum
cout << "The maximum integer value is: "
<< maximum( int1, int2, int3 );
// demonstrate maximum with double values
double double1, double2, double3;
cout << "\n\nInput three double values: ";
cin >> double1 >> double2 >> double3;
// invoke double version of maximum
cout << "The maximum double value is: "
<< maximum( double1, double2, double3 );
// demonstrate maximum with char values
char char1, char2, char3;
cout << "\n\nInput three characters: ";
cin >> char1 >> char2 >> char3;
// invoke char version of maximum
cout << "The maximum character value is: "
<< maximum( char1, char2, char3 ) << endl;
return 0; // indicates successful termination
} // end main