I was reading an article about cpp templates, and I found this syntax given.
1 2 3 4 5 6 7 8
template<class T, int N>
int array_size(const T (&a)[N])
{
return N;
}
int b[] = {1, 2, 3};
cout << array_size(b) << endl;
I couldnt understand the syntax. What are the arguments to this function array_size? And how can this print size of given array? Any help would be really appreciated.
If you had written array_size without templates it would have looked something like this:
1 2 3 4
int array_size(constint (&a)[3])
{
return 3;
}
This function takes a reference to an array of 3 integers as argument. Note that the array size is part of the array type.
The use of templates makes it work for any array type. The template parameter T specifies type of the array elements while the template parameter N specifies the number of elements in the array. When you pass an array to array_size you don't need to specify the template arguments because they can be inferred from the array type.
Calling array_size(b) in your example is the same as calling array_size<int, 3>(b) (T=int, N=3). It returns 3 because that's the value of N.
template<class T, int N>
there are 2 parameters in this template function – class T is the type template parameter and int N is the non-type or expression template parameter. There are certain restrictions upon the non-type template parameter that can be found here: http://en.cppreference.com/w/cpp/language/template_parameters
Interestingly, since C++17 non-type template parameter may even be deduced by the auto keyword: