openMSX
countof.hh
Go to the documentation of this file.
1 // countof(<array>) returns the number of elements in a statically
2 // allocated array. For example:
3 //
4 // int a[10];
5 // f(a, countof(a)); // f will be called with value 10 as 2nd parameter
6 //
7 //
8 // A naive implementation is this:
9 //
10 // #define countof(array) (sizeof(array) / sizeof(array[0]))
11 //
12 // This implementation has a problem. The following example compiles fine, but
13 // it gives the wrong result:
14 //
15 // int a[10];
16 // int* p = a;
17 // countof(p); // wrong result when called with pointer argument
18 //
19 //
20 // A better implementation is this:
21 //
22 // template<typename T, unsigned N>
23 // unsigned countof(T(&)[N])
24 // {
25 // return N;
26 // }
27 //
28 // The above example now results in a compilation error (which is good).
29 // Though in this implementation, the result of countof() is no longer a
30 // compile-time constant. So now this example fails to compile:
31 //
32 // int a[10];
33 // int b[countof(a)]; // error: array bound is not a constant
34 //
35 //
36 // The implementation below fixes both problems.
37 
38 #ifndef COUNTOF_HH
39 #define COUNTOF_HH
40 
41 // The following line uses a very obscure syntax:
42 // It declares a templatized function 'countofHelper'.
43 // It has one (unnamed) parameter: a reference to an array T[N].
44 // The return type is a reference to an array char[N]
45 // Note that this function does not need an implementation.
46 template<typename T, unsigned N> char (&countofHelper(T(&)[N]))[N];
47 
48 #define countof(array) (sizeof(countofHelper(array)))
49 
50 #endif
char(& countofHelper(T(&)[N]))[N]