Why we use non-type template arguments?

2020-02-06 07:55发布

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

4条回答
Root(大扎)
2楼-- · 2020-02-06 08:38

Another example of non type argument is:

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

Here the length of the data field is parameterised. Different instantiations of this struct can have different lengths of their arrays.

查看更多
Emotional °昔
3楼-- · 2020-02-06 08:39

To program at compile-time. Consider the WikiPedia example,

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

There are a bunch of other examples on the WikiPedia page.

EDIT

As mentioned in the comments, the above example demonstrates what can be done rather than what people use in real projects.

查看更多
乱世女痞
4楼-- · 2020-02-06 08:50

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);
}
查看更多
在下西门庆
5楼-- · 2020-02-06 08:51

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.

查看更多
登录 后发表回答