Re: template function issue
- From: Ulrich Eckhardt <eckhardt@xxxxxxxxxxxxxx>
- Date: Wed, 12 Dec 2007 13:01:55 +0100
George wrote:
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.
Define "does not work". Seriously, you have been asking questions here long
enough to have learned that a good error description is half the way to the
goal. It also shows that you have been doing your homework.
template<size_t size, typename T>
size_t GetArrayLength(const T(&arr)[size])
{
return size;
}
You can't pass an array to a function. Even if the function declaration
seems to suggest that it receives an array, it is in fact a pointer:
void foo( int x[4]);
is in fact the same as
void foo( int* x);
This is dangerous, because passing by value doesn't modify the parameters at
the caller's side, but since this isn't pass-by-value the parameters can be
modified!
Now, what you can do is to pass a reference-to-an-array to a function. In
that case, this does not decay to something like a pointer or a reference
to a pointer.
I hope this now also makes it clear why this can't work with a template: The
template requires parameters it can't deduce from the function parameters
(like the array size when there is no array passed around).
Uli
.
- Follow-Ups:
- Re: template function issue
- From: George
- Re: template function issue
- Prev by Date: Re: how the macro works
- Next by Date: Re: comma operator (was: how the macro works)
- Previous by thread: Re: how the macro works
- Next by thread: Re: template function issue
- Index(es):
Relevant Pages
|