template function issue

G

George2

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;
}


thanks in advance,
George
 
M

Michael DOUBEZ

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 said:
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;[/QUOTE]

     foo1(arr1);//arr1 is passed by reference
     std::cout << arr1  << std::endl;//prints "Gello ..."
     foo2(arr1);
     //following is error
     //foo3(arr1);[QUOTE]
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,224
Latest member
BettieToom

Latest Threads

Top