Why do we use template arguments without type?

I understand the concept, but I don’t know why I need to use non-type template arguments?

+4
source share
4 answers

There are many use cases, so let's look at a couple of situations in which they are needed:

returns the size of the array:

template <typename T, unsigned int N> unsigned int size(T const (&)[N]) { return N; } 

They are also extremely useful in metaprogramming patterns.

+14
source

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 many other examples on the WikiPedia page.

EDIT

As stated in the comments, the above example demonstrates what can be done , and not what people use in real projects .

+2
source

A real-life example consists of combining template arguments of a non-type type with the output of a template argument to output 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); } 
+2
source

Another example of a non type argument is

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

The length of the data field is set here. Different instances of this structure may have different lengths of their arrays.

0
source

Source: https://habr.com/ru/post/1435726/


All Articles