2012年11月16日 星期五

[C++] static array size macro

We usually get array size by using the following macro.
#define count_of(arg) (sizeof(arg) / sizeof(arg[0]))
But this code would not get any compile error when we pass the pointer as argument like below:
void Test(int C[3])
{
  int A[3];
  int *B = Foo();
  size_t x = count_of(A); // Ok
  x = count_of(B); // Error
  x = count_of(C); // Error
}
One way is to declare like this: (pass the reference which indicate the number of array)
void Test(int (&C)[3])
{
  ...
}
// reference http://www.cplusplus.com/articles/D4SGz8AR/
Now the following code snippet is creating template function. The function template is named ArraySizeHelper, for a function that takes one argument, a reference to a T [N], and returns a reference to a char [N]. If you give it a non-array type (e.g. a T *), then the template parameter inference will fail.
// reference http://www.viva64.com/en/a/0074/
// http://stackoverflow.com/questions/6376000/how-does-this-array-size-template-work
template 
char (&ArraySizeHelper(T (&array)[N]))[N];
#define arraysize(array) (sizeof(ArraySizeHelper(array)))

沒有留言:

張貼留言