在實例化類模板時,需要在尖括號中間指明類型;但是在實例化函數模板時,可以不寫尖括號極其內部類型,因爲函數模板具有參數類型推斷功能。如下:
#include <iostream>
using namespace std;
template<typename T> const T& my_min(const T& a, const T& b) {
return (a < b) ? a : b;
}
int main()
{
int x = 3;
int y = 4;
int z = my_min(x, y);
int i = 3;
double j = 4;
int k0 = my_min(i, j);
int k1 = my_min<int>(i, j);
}
當輸入參數爲同一類型時,實例化函數模板時不必寫尖括號極其類型,函數模板會根據輸入參數的類型進行type deduction, 如:
<pre name="code" class="cpp">int x = 3;
int y = 4;
int z = my_min(x, y);
但是,當輸入參數的類型不一致時,函數模板則無法推斷類型,程序會報錯,如:
int i = 3;
double j = 4;
int k0 = my_min(i, j);
這時需要使用尖括號,並在其內部指定類型,如:
int k1 = my_min<int>(i, j);
函數模板還可以推斷出數組的大小(dimensions), 當數組以指針或引用傳遞時,會附帶數組大小信息,如下:
//: C05:ArraySize.cpp
#include <cstddef>
using std::size_t;
template<size_t R, size_t C, typename T>
void init1(T a[R][C]) {
for(size_t i = 0; i < R; ++i)
for(size_t j = 0; j < C; ++j)
a[i][j] = T();
}
template<size_t R, size_t C, class T>
void init2(T (&a)[R][C]) { // Reference parameter
for(size_t i = 0; i < R; ++i)
for(size_t j = 0; j < C; ++j)
a[i][j] = T();
}
int main() {
int a[10][20];
init1<10,20>(a); // Must specify
init2(a); // Sizes deduced
} ///:~
參考:Bruce Eckel. Thinking In C++ Volume 2: Practical Programming. page242.