Home >Backend Development >C++ >How Can a Template Function Determine the Size of a C Array at Compile Time?
Template Function for Determining Array Size
Consider the template function below:
template<typename T, size_t n> size_t array_size(const T (&)[n]) { return n; }
The purpose of this template is to determine the size of an array passed as an argument. Passing an array by reference preserves its size, rather than simply obtaining a pointer.
Explanation
To understand this, consider the following:
In our template function, the array is passed by reference, ensuring that its size is captured. The template automatically deduces the size (n) and element type (T). This allows us to utilize it as:
size_t array_size(const int (&)[3]) { return 3; }
which can be used as follows:
size_t size_of_a = array_size(a);
Advanced Usage
There is a variation of this technique that allows for compile-time size determination:
template<typename T, size_t n> char (& array_size(const T (&)[n]) )[n];
This template returns a reference to an array of type char with size n. As such, the following code will give the size of the passed array at compile time:
size_t size_of_a = sizeof(array_size(a));
This construct enables compile-time-determined array sizes, supporting actions such as:
int havingSameSize[sizeof(array_size(a))];
The above is the detailed content of How Can a Template Function Determine the Size of a C Array at Compile Time?. For more information, please follow other related articles on the PHP Chinese website!