Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use non-type template arguments?

I understand the concept but i don't know why i require to use non-type template arguments ?

like image 482
oiyio Avatar asked Nov 30 '22 05:11

oiyio


2 Answers

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.

like image 140
juanchopanza Avatar answered Dec 04 '22 14:12

juanchopanza


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);
}
like image 37
Kerrek SB Avatar answered Dec 04 '22 12:12

Kerrek SB