The array decayed to a pointer.
list
is an int*
in len()
and int[5]
in main
.
As mentioned here there are two possible fixes:
- Use a reference
- Explicitly use a reference to array type
If you use a reference then it will work (the pointer does not decay), but you would still have to calculate the number of elements:
#include <iostream>
template <typename list_type>
int len(list_type &list) {
std::cout << sizeof(list) << '\n';
return (sizeof(list) / sizeof(list[1]));
}
int main() {
int list[5] = {1, 2 ,3 ,5 ,4};
std::cout << sizeof(list) << "\n";
auto element_count = len(list);
std::cout << "There are " << element_count << " elements in the list.\n";
}
For the second option, you get the size of the array at compile time:
#include <iostream>
template <typename list_type, size_t N>
int len(list_type (&list) [N]) {
std::cout << sizeof(list) << '\n';
return N;
}
int main() {
int list[5] = {1, 2 ,3 ,5 ,4};
std::cout << sizeof(list) << "\n";
auto element_count = len(list);
std::cout << "There are " << element_count << " elements in the list.\n";
}