A template from the chrome code

Source: Internet
Author: User

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 ^_^.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.