Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysterious oneliner template code, any one? [duplicate]

I was reading this page : C++ Tip: How To Get Array Length. The writer presented a piece of code to know the size of static arrays.

template<typename T, int size>
int GetArrLength(T(&)[size]){return size;} // what does '(&)' mean ?
.
.
.
int arr[17];
int arrSize = GetArrLength(arr); // arrSize = 17

Could anyone please shed the light on this code, because I couldn't understand how it really works.

like image 461
Khaled Alshaya Avatar asked Jan 24 '23 09:01

Khaled Alshaya


1 Answers

The function is passed a reference (&) to an array of type T, and size size.

like image 199
jalf Avatar answered Jan 26 '23 00:01

jalf