Re: template function issue



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

.



Relevant Pages

  • Re: Determining array size
    ... if you make the template version an inline function. ... Your version suffers from the big problem that is will compile for pointers. ... Its quite common for an array to change to a pointer, ...
    (comp.lang.cpp)
  • Re: char **argv & char *argv[]
    ... "pointer to pointer to char". ... >> pointer)) pointing to the first element of an array. ... so we have to start adding more context. ... type "pointer to char", rather than "array MISSING_SIZE of char". ...
    (comp.lang.c)
  • Re: Who owns the variable in my header file ?
    ... to check the subscripts to the array and trap on error conditions. ... cast one type of pointer into another; you wouldn't then be able to step ... language trying to be C like, ... One reason being that the programmer can possible ...
    (comp.lang.c)
  • Re: why cannot assign to function call
    ... hypothetical C-like languages, ... sizeof business would still indicate that a pointer was being passed. ... talk about variables of an array type. ... the earlier version of the standard didn't have numbered ...
    (comp.lang.python)
  • Re: multi dimensional arrays as one dimension array
    ... please - where does the standard say that such a conversion ... Pointer conversion yields a pointer to the same object as ... exist only where there are array declarations. ...
    (comp.lang.c)