Question

In llvm-3.4\include\llvm\ADT\STLExtras.h, i see this function:

/// Find the length of an array.
template<class T, std::size_t N>
inline size_t array_lengthof(T (&)[N]) {
  return N;
}

This function returns the array length:

int main(){
  const char spaces[] = "dededesdf sdf sdfs fdsf"
                        "dadsds jsdfdfs ffjsdklfj dsfds";
  std::cout << array_lengthof(spaces); //prints 54
  return 0;
}

Can someone explain how the function works and also what the parameter T (&)[N] means? Are there any scenarios in which this function will not work?

Was it helpful?

Solution 2

array_lengthof is a template function. This function is generated at compile time for all combination of array type and size (you pass to this function in your code) during compile time.

So if you call this function for int a[10]; Function call would be converted implicitly by compiler to

array_lengthof<int, 10>(a).

Parameter T (&param)[N] means param is a reference to an int array of size N. (N being a compile time constant)

OTHER TIPS

That's a non-type template parameter. It works by leveraging the template argument deduction mechanism. Basically, it tries to figure out template arguments that will cause a match.

It will work as long as it is a real array. It won't work for pointers to a chunk of memory, like:

int *array = new int[10];
array_lengthof(array); // ERROR.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top