相关疑难解决方法(0)

这个C++代码是什么意思?

以下代码返回堆栈分配的数组的大小:

template<typename T, int size>
int siz(T (&) [size])
{
    return size;
}
Run Code Online (Sandbox Code Playgroud)

但我无法理解语法.特别是T (&) [size]部分......

c++ templates

22
推荐指数
2
解决办法
1022
查看次数

宏定义ARRAY_SIZE

在Google V8项目中读取globals.h时遇到以下宏定义.

// The expression ARRAY_SIZE(a) is a compile-time constant of type
// size_t which represents the number of elements of the given
// array. You should only use ARRAY_SIZE on statically allocated
// arrays.

#define ARRAY_SIZE(a)                               \
  ((sizeof(a) / sizeof(*(a))) /                     \
  static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
Run Code Online (Sandbox Code Playgroud)

我的问题是后半部分:static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))).我想到的一件事是:由于后一部分将始终求1值为(类型)size_t,整个表达式将被提升为size_t.

如果这个假设是正确的,那么还有另一个问题:由于sizeof运算符的返回类型是size_t,为什么需要这样的推广?以这种方式定义宏有什么好处?

c c++ macros

13
推荐指数
4
解决办法
2万
查看次数

为什么 MSVC _count_of 实现在 sizeof 的结果上加 0?

我一直在阅读_countofMSVC 中宏的实现,发现了一个我无法解释的细节。它是通过一个__crt_countof宏实现的,该宏在 C++ 上扩展为(sizeof(*__countof_helper(_Array)) + 0)是标题中的相关代码)。为什么在+ 0那里?没有它会出什么问题?

c++ msvcrt visual-c++

6
推荐指数
1
解决办法
166
查看次数

理解_countof宏

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

#define _myCountOf(_Array) (sizeof(*__countof_helper1(_Array)) + 0)
Run Code Online (Sandbox Code Playgroud)

我试图理解 _countof 宏,但无法理解它如何能够计算数组的大小。请有人一点一点解释上面的代码

c++ templates

0
推荐指数
1
解决办法
3976
查看次数

标签 统计

c++ ×4

templates ×2

c ×1

macros ×1

msvcrt ×1

visual-c++ ×1