George2 a écrit :
Hello everyone,
In the following code, how GetArrayLength(arr1) is matched to template
function size_t GetArrayLength(const T(&arr)[size])?
T(&arr)[size] is considered as a type. The same you could write a
specific typedef:
typedef int array_int[10];
The template matches the type <T,N> "array of N elements of type T".
My confusion is
how arr1 is matched to const T(&arr)[size]? I have tried to change
const T(&arr)[size] to const T(arr)[size]) but it does not work.
For historical reasons arrays are no passed by values but are
implicitely cast into pointer so the following code doesn't pass by
value but takes a pointer:
void foo1(char array[12])
{
array[0]='G';
}
and the code is ok when arr1 used with:
void foo2(char array[42])
{
array[0]='G';
}
But not when using a type:
void foo3(char (&array)[42])
{
array[0]='G';
}
[Code]
template<size_t size, typename T>
size_t GetArrayLength(const T(&arr)[size])
{
return size;
}
int main()
{
char arr1[] = "Hello World";
std::cout << GetArrayLength(arr1) << std::endl;
foo1(arr1);//arr1 is passed by reference
std::cout << arr1 << std::endl;//prints "Gello ..."
foo2(arr1);
//following is error
//foo3(arr1);
return 0;
}
[/Code]
.