template function to determine size of an array

How do you determine the size of an array? Well obviously for dynamic array you have to know how much memory you allocated but for statically allocated array we have been defining macro NUM_ELEMS like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <iostream>

#define NUM_ELEMS(arr) sizeof((arr))/sizeof((arr[0]))

int main()
{
    int arr[] = {1,2,3,4,5,6,7,8,9};
    int numElements = NUM_ELEMS(arr);

    std::cout << numElements << std::endl;

    return 0;
}

What if I want to do this using templates?

1
2
3
4
5
template<class T, size_t N>
int num_elements(const T (&arr) [N])
{
    return N;
}

Here we have template function that is parametrized for a type and number, and the argument list matches an array of size N. So the code looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

#define NUM_ELEMS(arr) sizeof((arr))/sizeof((arr[0]))

template<class T, size_t N>
int num_elements(const T (&arr) [N])
{
    return N;
}

int main()
{
    int arr[] = {1,2,3,4,5,6,7,8,9};
    int numElements = NUM_ELEMS(arr);

    std::cout << numElements << std::endl;
    std::cout << num_elements(arr) << std::endl;

    return 0;
}
 
C++