C++ Templates 的另类用法

类别:编程语言 点击:0 评论:0 推荐:
先来看一看下面这个 template. 

extern "C++" // templates cannot be declared to have 'C' linkage
template <typename T, size_t N>
char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];

想知道这个的template做什么用的吗?它的目的不是生成可调用的template function, 而且根本没有implement. 也没有任何人需要调用它。

你是否考虑过带类型检查的 ARRAYSIZE macro宏?
ARRAYSIZE 一般的定义是:
 #define ARRAYSIZE(x) (sizeof(x)/sizeof((x)[0]))


但是这个宏在下面代码中会带来灾难性的后果,而且编译器不会有 warning。
(though none will make this type of mistake in general  )

Struct Foo { CHAR _ch[10]; };
Foo * pFoo;
ARRAYSIZE(pFoo); // will ==0

怎么解决呢?下面是从winnt.h中看到的:

// 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)

真是“没有做不到,只有想不到”。不过,这东西有点太Hack了。不看注释太难理解了,注释在下面了。

// 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 reference to an array of N chars.
//
// typedef char array_of_char[N];
// typedef T3 & reference_to_array_of_char;
//
// sizeof(array_of_char) == N
// sizeof(reference_to_array_of_char) == N
//
// reference_to_array_of_char RtlpNumberOf(reference_to_array_of_T);
//
// We never even call RtlpNumberOf, we just take the size of its return type.
// We do not even implement RtlpNumberOf, we just decare it.
//

以上是我自己的理解,不知道是不是正确,欢迎讨论。

本文地址:http://com.8s8s.com/it/it23973.htm