2012-09-23 62 views

回答

14

有許多用例,那麼讓我們來看看一對夫婦的情況下,他們是不可缺少的,其中:

  • 固定大小的數組或matrix類,例如見C++ 11 std::arrayboost::array

  • 一種可能實現的std::begin爲陣列,或需要一個固定的尺寸爲C風格陣列的大小,例如任何的代碼:

返回的數組的大小:

template <typename T, unsigned int N> 
unsigned int size(T const (&)[N]) 
{ 
    return N; 
} 

它們在模板元編程中也非常有用。

+0

+1在這個迴應中的每一個原因(如果我能+3它我會)。 – WhozCraig

2

在編譯時進行編程。考慮WikiPedia例如,

template <int N> 
struct Factorial { 
    enum { value = N * Factorial<N - 1>::value }; 
}; 

template <> 
struct Factorial<0> { 
    enum { value = 1 }; 
}; 

// Factorial<4>::value == 24 
// Factorial<0>::value == 1 
const int x = Factorial<4>::value; // == 24 
const int y = Factorial<0>::value; // == 1 

還有一堆的維基百科頁面上的其他例子。

編輯

正如在評論中提到的,上面的例子說明了什麼可以做而不是人們在現實項目用什麼。

+0

我不瞭解你,但是「我們」不會在編譯時使用它來編程。 :\ – Mehrdad

+4

這僅僅證明了模板功能強大,但並未顯示它們如何在實際代碼中使用。 – hvd

+0

好的,我會用一個更好的例子更新我的答案。 – Hindol

2

一個真實世界的例子來自非類型模板參數與模板參數推導組合以推導數組的大小:

template <typename T, unsigned int N> 
void print_array(T const (&arr)[N])  // both T and N are deduced 
{ 
    std::cout << "["; 
    for (unsigned int i = 0; i != N; ++i) 
    { 
     if (i != 0) { std::cout << ", "; 
     std::cout << arr[i]; 
    } 
    std::cout << "]"; 
} 

int main() 
{ 
    double x[] = { 1.5, -7.125, 0, std::sin(0.5) }; 
    print_array(x); 
} 
0

非類型參數的另一個例子是:

template <int N> 
struct A 
{ 
    // Other fields. 
    int data[N]; 
}; 

這裏數據字段的長度被參數化。這個結構的不同實例可以有不同的數組長度。

相關問題