Template <typename T, size_t N>
Char (& ArraySizeHelper (T (& array) [N]) [N];
# Define arraysize (array) (sizeof (ArraySizeHelper (array )))
Then, the arraysize macro can be used to obtain the array size during compilation.
When I first read this code, I thought it was very tangled. I sent it to my classmates for discussion and then I thought it was a bit eye-catching. In fact, this is a way to calculate the array size during compilation. Of course we can also write it.
# Define arraysize (array) (sizeof (array)/sizeof (array [0, I think it is the most difficult to write this because efficiency is taken into account, avoiding the division operation in the above writing. The division operation is the most time-consuming in the four arithmetic operations (C ++, which cannot afford to hurt, high efficiency and lower readability)
You can write a small program to test it:
1 # include "stdafx. h"
2 # include <stdio. h>
3 # include <stdlib. h>
4
5 template <typename T, size_t N>
6 char (& ArraySizeHelper (T (& array) [N]) [N];
7 # define arraysize (array) (sizeof (ArraySizeHelper (array )))
8
9 int _ tmain (int argc, _ TCHAR * argv [])
10 {
11
12 double a [200];
13
14 double * B = new double [100];
15 int cnt = arraysize ();
16 printf ("% d", cnt );
17
18 system ("pause ");
19
20 return 0;
21} the output is 200. Replace array a with int, And the char result is still 200. This is easy to understand, because the template is used for programming, generic programming ....... however, this method can only determine the size of the compiled array. Otherwise, use a dynamic array. For example, replace a In line 15 of the Code with B, compilation fails .......
In fact, the general process is: T [N] reference-> char [N] reference, and finally sizeof (char [N]). char is actually a Byte, and the output is N ^_^.