count_of 的作用是编译时静态获取数组元素数目,C中必须使用宏实现:
#define count_of(a) (sizeof(a)/sizeof(a[0]))
C++中还可以使用模板实现:
template<typename T,size_t N> inline size_t count_of( T (&)[N] ) { return N; }
宏实现的优点是:C和C++均可使用
模板实现优点是:可以禁止掉不合法的应用
C宏实现的事例代码:
#include <stdio.h>
#define count_of(a) (sizeof(a)/sizeof(a[0]))
int main( void )
{
char a[12];
int b[3][4];
char* p = 0;
printf( "%u\n", count_of(a) ); // 输出12
printf( "%u\n", count_of(b) ); // 输出3
printf( "%u\n", count_of(p) ); // 用法错误,但编译时却无法检测出来
}
C++模板实现的事例代码:
#include <iostream>
template<typename T,size_t N> inline size_t count_of( T (&)[N] ) { return N; }
int main( void )
{
char a[12];
int b[3][4];
char* p = 0;
std::cout << count_of(a) << std::endl; // 输出12
std::cout << count_of(b) << std::endl; // 输出3
// std::cout << count_of(p) << std::endl; // 编译时直接报错
}
注:像VC++6.0之类的烂编译器不支持参数数组引用,请使用 g++ 或 vc++8.0 。

评论