none
关于ARRAYSIZE宏的问题 RRS feed

答案

全部回复

  • 需要Visual C++ 2005或者更高版本
    MSMVP VC++
    • 已标记为答案 十二晨 2009年5月21日 10:09
    2009年5月19日 16:53
    版主
  • // RtlpNumberOf is a function that takes a reference to an array of N Ts.
    //
    // typedef T array_of_T[N];
    // typedef array_of_T &reference_to_array_of_T;
    //
    // RtlpNumberOf returns a pointer to an array of N chars.
    // We could return a reference instead of a pointer but older compilers do not accept that.
    //
    // typedef char array_of_char[N];
    // typedef array_of_char *pointer_to_array_of_char;
    //
    // sizeof(array_of_char) == N
    // sizeof(*pointer_to_array_of_char) == N
    //
    // pointer_to_array_of_char RtlpNumberOf(reference_to_array_of_T);
    //
    // We never even call RtlpNumberOf, we just take the size of dereferencing its return type.
    // We do not even implement RtlpNumberOf, we just decare it.
    //
    // Attempts to pass pointers instead of arrays to this macro result in compile time errors.
    // That is the point.
    //
    extern "C++" // templates cannot be declared to have 'C' linkage
    template <typename T, size_t N>
    char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];

    #define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A)))

    #define ARRAYSIZE(A)    RTL_NUMBER_OF_V2(A)

    这个宏是调用RtlpNumberOf 的,RTL开头的一般都是内核函数.

    还有一种定义方法,这种方法也是可以获得数组长度的.
    #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0]))


    Hello world
    2009年5月21日 3:20
    版主