As some practice for using templates, I tried to write a function template to find the size of an array:
template <typename T>
size_t arraySize(T array[]) {
return (sizeof(array)/sizeof(T));
}
I then tried to test the template with a few arrays of different data types alongside regular sizeof(array)/sizeof(datatype) computations as follows:
int main(){
int arr1[20];
char arr2[20];
double arr3[20];
cout << arraySize(arr1) << ' ' << arraySize(arr2) << ' ' << arraySize(arr3) << endl;
cout << sizeof(arr1)/sizeof(int) << ' ' << sizeof(arr2)/sizeof(char) << ' ' << sizeof(arr3)/sizeof(double);
}
The output is
2 8 1
20 20 20
Why does this template not work as expected?
Note: I am aware of the existence of other questions relating to array size with templates on Stack Overflow (such as this one), but I'm mainly confused as to why this specific code doesn't work.