Thursday, 26 February 2015

Size Of Array Using Templates


Here is the sample program that help us compute the size of the array.

Arpproach 1:
template<typename T, int size>
size_t asz(T (&)[size]) { return size; }

int _tmain(int argc, _TCHAR* argv[])
{
int a[12], b[20];
const int sz1 = asz(a);
const int sz2 = asz(b);


return 0;
}

How is this working?


int asz(T (&)[size]) { return size; }

The parameter to asz function is the un-named reference parameter of size elements.

When asz(a) is called, basically we are passing the type as int which maps to template parameter 'T' and array is mapped to the un-named reference parameter with size elements as compiler internally pass the size to the method. That's why when we return we get the exact size of the array.

We can simple find out the size of the array using sizeof(arr)/sizeof(type). but it wont work in most of the cases where arr is not of pointer type.

Approach 2:



int size = (&arr)[1] - arr;
 
arr and &arr  both points to the address of the array. But when we do &arr[1],
it points to the last element of the array where as arr[1] points to first element 
of the array.
 
 
image 
Assume arr is of int with 5 elements. If you do address/pointer arithmetic it 
basically jumps by its type(5 int) bytes.
 

No comments:

Post a Comment

AWS Data Pipeline Services

https://www.youtube.com/watch?v=tykcCf-Zz1M