Doubt in template syntax

Hello

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.

Thanks
The parameter is an array passed by reference. See:

http://stackoverflow.com/questions/10007986/c-pass-an-array-by-reference
If you had written array_size without templates it would have looked something like this:

1
2
3
4
int array_size(const int (&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.
Last edited on
std::size overload (2) (C++17) http://en.cppreference.com/w/cpp/iterator/size

1
2
template < typename T, std::size_t N >
constexpr std::size_t size( const T (&array)[N] ) noexcept ;


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:
1
2
3
4
template<auto n> 
struct myNonType{ /* … */ };
myNonType<5> mNT_1{};//OK, it's int
myNonType<'a'> mNT_2{}; //OK, it's char 


A widespread use of non-type template parameter is of course std::array that is declared as:
1
2
template <class T, std::size_t N>
struct array;

http://en.cppreference.com/w/cpp/container/array
so std::array<int, 5> and std::array<int, 6> are entirely different types
Thank you so much everyone. I was able to understand this one better. Really helps in coming to this forum and interacting with such experts :)
Topic archived. No new replies allowed.