非型別模板引數
除了作為模板引數的型別,我們可以宣告符合以下條件之一的常量表示式的值:
- 積分或列舉型別,
- 指向物件的指標或指向函式的指標,
- 左值引用物件或左值引用函式,
- 指向成員的指標,
std::nullptr_t
。
與所有模板引數一樣,可以通過 Template Argument Deduction 顯式指定,預設或派生非型別模板引數。
非型別模板引數用法示例:
#include <iostream>
template<typename T, std::size_t size>
std::size_t size_of(T (&anArray)[size]) // Pass array by reference. Requires.
{ // an exact size. We allow all sizes
return size; // by using a template "size".
}
int main()
{
char anArrayOfChar[15];
std::cout << "anArrayOfChar: " << size_of(anArrayOfChar) << "\n";
int anArrayOfData[] = {1,2,3,4,5,6,7,8,9};
std::cout << "anArrayOfData: " << size_of(anArrayOfData) << "\n";
}
顯式指定型別和非型別模板引數的示例:
#include <array>
int main ()
{
std::array<int, 5> foo; // int is a type parameter, 5 is non-type
}
非型別模板引數是實現模板重現的方法之一,並且可以進行超程式設計 。