在这个“元素数量"中进行虚拟加法的目的是什么?宏?

2022-01-11 00:00:00 arrays macros visual-c++ templates c++

Visual C++ 10 附带 stdlib.h,其中包含此 gem:

Visual C++ 10 is shipped with stdlib.h that among other things contains this gem:

template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper(UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];

#define _countof(_Array) (sizeof(*__countof_helper(_Array)) + 0)

它使用一个巧妙的模板技巧来推断数组大小和防止指针被传递到__countof.

宏定义中+0的作用是什么?它解决了什么问题?

What's the purpose of + 0 in the macro definition? What problem does it solve?

推荐答案

引用 这里

我做了这个改变;我通常不破解 CRT,但这个是不重要的.+ 0 使虚假的警告 C6260: sizeof * sizeof通常是错误的.您打算使用字符数还是字节数count?" 来自/analyze,当有人写 _countof(arr) * sizeof(T).

I made this change; I don't usually hack the CRT, but this one was trivial. The + 0 silences a spurious "warning C6260: sizeof * sizeof is usually wrong. Did you intend to use a character count or a byte count?" from /analyze when someone writes _countof(arr) * sizeof(T).

相关文章