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:

#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?

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:

#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;
}