I understand the concept but i don't know why i require to use non-type template arguments ?
There are many use-cases, so let's look at a couple of situations where they are indispensable:
Fixed sized array or matrix classes, see for example C++11 std::array or boost::array.
A possible implementation of std::begin for arrays, or any code that needs the size of a fixed size C style array, for example:
return the size of an array:
template <typename T, unsigned int N>
unsigned int size(T const (&)[N])
{
return N;
}
They are also extremely useful in template metaprogramming.
A real-world example comes from combining non-type template arguments with template argument deduction to deduce the size of an array:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With