template function issue



 DEVELOP > c-Plus-Plus > template function issue

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "George2"
Date: 12 Dec 2007 03:41:58 AM
Object: template function issue
Hello everyone,
In the following code, how GetArrayLength(arr1) is matched to template
function size_t GetArrayLength(const T(&arr)[size])? 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.
[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;
return 0;
}
[/Code]
thanks in advance,
George
.

User: "Michael DOUBEZ"

Title: Re: template function issue 12 Dec 2007 04:58:37 AM
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]

.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER