1. 程式人生 > >C++ 非型別模版引數

C++ 非型別模版引數

16.1.5. Nontype Template Parameters

A  template parameter need not be a type.

// initialize elements of an array to zero
template <class T, size_t N> void array_init(T (&parm)[N])
{
for (size_t i = 0; i != N; ++i) {
parm[i] = 0;
}
}

A  template nontype parameter is a constant value inside the template definition. A nontype parameter can be used when constant expressions are requiredfor example, as we do hereto specify the size of an array.

When array_initis called, the compiler figures out the value of the nontype parameter from the
array argument:


int x[42];
double y[10];
array_init(x); // instantiates array_init(int(&)[42]
array_init(y); // instantiates array_init(double(&)[10]