This function correctly prints out size of an array in a function.
Can someone please explain to me how it works? Many thanks.
#include <iostream>
using namespace std;
template <int SIZE>
void f(const int (&array)[SIZE])
{
cout << sizeof(array) << endl;
}
int main()
{
int array[3] = {3,4,9};
cout << sizeof(array) << endl;
f(array);
return 0;
}
Sorry, I'm still a little confused. I thought that we are passing "array" which is pointer to an integer (or first element of array) to f. How does f know that array has 3 elements? In absence of the template, I just get the size of the pointer "array" which is 4. I think there is something very basic here that I am not getting. Thanks a lot.
also, in the c++ tutorial, template is described as:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
Why are we using int instead of class or typename keywords?
void PtrToFirst( int* ptr )
{
// here, the array could be any size. No way to know
}
void ByRef( int (&ar)[5] )
{
// here, we know we have an array of exactly 5 elements
// it's as if 'ar' was declared in this function as: int ar[5];
}
int main()
{
int example[5];
PtrToFirst(example); // OK
ByRef(example); // OK
int foo[6];
PtrToFirst(foo); // OK
ByRef(foo); // ERROR, int[6] is not int[5]
int* ptr = newint[5];
PtrToFirst(ptr); // OK
ByRef(ptr); // ERROR, int* is not int[5]
}
Here, the ByRef function takes an array of 5 elements. No more and no less. What's more, it has to be an actual array, not a pointer to dynamically allocated memory.
Using templates, we can change that stern '5' into a variable:
template <int S> // S will be the array size
int arraysize(constint (&array)[S]) // the array is of size S
{
return S; // return S, the number of elements in the array
}
int main()
{
int ex5[5];
arraysize<5>( ex5 ); // call arraysize with S=5. OK
int ex6[6];
arraysize<6>( ex6 ); // also OK, here, S=6
// the neat thing is, the compiler can automatically figure out S based on the
// array you give it. So you don't need to explicitly say <5> or <6>
arraysize( ex5 ); // compiler automatically figures S=5. OK
arraysize( ex6 ); // compiler automatically figures S=6. OK
// however, non-arrays will still fail for the same reason as before -- pointers are not arrays:
int* foo = newint[5];
arraysize( foo ); // ERROR
arraysize<5>( foo ); // ERROR -- even if we explicitly specify S. 'foo' is not an array name