If arrays don't know their own size, how come this works?

I found an interesting piece of code. I need someone to explain to me how come this works, if arrays don't know their own size:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "std_lib_facilities.h"

template<class T, int s> void double_elements(T (&arg)[s])
{
	for(int i = 0; i < s; ++i) arg[i] *= 2;
}

int main()
{
	int a[10];
	for(int i = 0; i < 10; ++i) a[i] = i + 1;
	double_elements(a); // Note: we don't pass the size to the function, just the array
	for(int i = 0; i < 10; ++i) cout << a[i] << '\n';
	keep_window_open();
	return 0;
}
Last edited on
double_elements() is a function template.
Templates are a way to leave it to the compiler to fill in "missing" data, such as type.

The compiler obviously realizes that int a[10]; is an array with a length of 10 elements.

So the array itself still doesn't know its own size, but the compiler does, and sets s accordingly (in this case to be 10).
Thank you very much! Now I understand everything.
Topic archived. No new replies allowed.