Home >Backend Development >C++ >How Does a C Template Function Determine the Size of an Array?

How Does a C Template Function Determine the Size of an Array?

DDD
DDDOriginal
2024-12-05 17:31:11662browse

How Does a C   Template Function Determine the Size of an Array?

Understanding the "size of array" Template Function

This code employs a template function to determine the length of an array, but its inner workings can be enigmatic. Let's delve into how it accomplishes this task.

Parameter Demystification

The function parameter, T(&)[size], might initially seem perplexing. Decoding it from inside out reveals a reference to an unnamed array of size size with type T. This means it accepts references to any array, where the array's type and size are specified by the template parameters.

Template Deduction in Action

When the function is called with an array, such as:

int a[10];
GetArrLength(a);

The compiler attempts to infer the template parameters. To match the parameter type, T must be int, and size must be 10 (resulting in a parameter that references an array of 10 integers). The function then returns the size, providing the number of elements in the array.

Addressing Potential Issues

This code has two potential issues. Firstly, sizes cannot be negative, so a signed type should not be used for the template parameter or return type. Instead, an unsigned type should be utilized, such as std::size_t:

template<typename T, std::size_t Size>
std::size_t GetArrLength(T(&amp;)[Size]) { return size; }

Secondly, the function's result is not a constant expression, despite the constant nature of array sizes. For enhanced usability, a constant expression is preferred:

template <std::size_t N>
struct type_of_size
{
    typedef char type[N];
};

template <typename T, std::size_t Size>
typename type_of_size<Size>::type&amp; sizeof_array_helper(T(&amp;)[Size]);

#define sizeof_array(pArray) sizeof(sizeof_array_helper(pArray))

Using this technique, you can retrieve the size of an array as a constant-expression:

int a[10];
const std::size_t n = sizeof_array(a); // constant-expression!

The above is the detailed content of How Does a C Template Function Determine the Size of an Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn