How does the snippet I posted handle pointers? |
It doesn't. It's impossible to get the size of an array if all you have is a pointer to the first argument.
And can you explain the snippet like I had asked? I didn't understand it. |
I guess you mean the following code.
1 2 3 4 5
|
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
return N;
}
|
Just ignore
constexpr and
noexcept. They are not relevant to our discussion.
Let's start with something simpler...
The following is a function that accepts an int array of size 10 by reference and returns the size (which is of course 10).
1 2 3 4
|
std::size_t size(const int (&array)[10])
{
return 10;
}
|
The syntax might look a bit weird but that's how you have to write it when you deal with pointers and references to arrays.
Now, if we want this to work for any type T we can turn it into a template.
1 2 3 4 5
|
template <class T>
std::size_t size(const T (&array)[10])
{
return 10;
}
|
We can now use this function template to get the size of any array of size 10.
1 2 3 4
|
int arr[10];
float arr2[10];
std::cout << size(arr) << '\n'; // calls size<int>(arr) which returns 10
std::cout << size(arr2) << '\n'; // calls size<float>(arr2) which returns 10
|
But we cannot yet use it for arrays that has a size other than 10.
1 2 3
|
int arr3[5];
std::cout << size(arr3) << '\n'; // error, because size<int> expects an int array of
// size 10 but got an int array of size 5.
|
To fix this we add another template parameter N that represents the size of the array.
1 2 3 4 5
|
template <class T, std::size_t N>
std::size_t size(const T (&array)[N])
{
return N;
}
|
Now we can use it for array types of any size.
1 2
|
int arr3[5];
std::cout << size(arr3) << '\n'; // OK, calls size<int, 5>(arr3) which returns 5
|