Understand this line?

For some reason, I can't understand these lines. They work and compile fine, but I don't know what they do.
1
2
template <typename T, int N>
char ( &Array( T(&)[N] ) )[N];

It looks like it's a reference to a function typecast as a char and with a subscript...help?
Looks like:

Array is a function that takes a reference to an array of T and returns a reference to an array of char.

But the code for the function itself should confirm or deny that.
That's the weird thing...this code stands alone. The code that uses it is at http://www.dreamincode.net/code/snippet347.htm
What they say is "it converts an array of type T to an array of type char" but I don't get how that one line does it...
To be honest that's a bit silly; to sacrifice readability such that you can't actually read it, and have to decipher it, just for the sake of having it on one line. Unless the point was to have as short a program as possible, in which case it's just about acceptable.
Last edited on
It works like this:
It is as I say a Array is a function that takes a reference to an array of type T and size N and returns a reference to an array of char of size N.

Notice there is no body to this function.

A function has a size - this size is the sizeof( return_type) unless the return type is void.

so if you have a function:

int some_func();

then sizeof(some_func() ) is the same as sizeof(int).

So the return type of char ( &Array( T(&)[N] ) )[N]; is char[N] and sizeof(char[N]) will be N

As we are only interested in the sizeof the return type - the body of the function need not be provided as we do not plan on actually calling the function.
Last edited on
Aah, I get it now. Thank you!
Topic archived. No new replies allowed.