这个数组大小模板如何工作? [英] How does this Array Size Template Work?

查看:101
本文介绍了这个数组大小模板如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个片段

  template< typename T,size_t N& 
char(& ArraySizeHelper(T(& array)[N]))[N];
#define arraysize(array)(sizeof(ArraySizeHelper(array)))

文章 http://software.intel.com/en-us/articles/pvs- studio-vs-chromium /



我已经看过其他模板来做同样的事情,像这一样



使用模板获取数组大小和结束地址



,我理解这些,但我一直在使用这一个。



任何帮助将不胜感激。

解决方案

函数模板命名为 ArraySizeHelper ,对于接受一个参数的函数,引用 T [N] ,并返回对 char [N]



宏传递你的对象(比方说 X obj [M] )作为参数。编译器推断 T == X N == M 。因此它声明一个返回类型为 char(&)[M] 的函数。宏然后用 sizeof 包装这个返回值,所以它真的做 sizeof(char [M]) M



如果你给它一个非数组类型(例如 T * ),那么模板参数推断将失败。



如下面的@Alf指出的,这个混合模板宏系统的优点替代模板方法是这给你一个编译时常量。


I came across this snippet

template <typename T, size_t N>  
char (&ArraySizeHelper(T (&array)[N]))[N];  
#define arraysize(array) (sizeof(ArraySizeHelper(array))) 

in this article http://software.intel.com/en-us/articles/pvs-studio-vs-chromium/

I've seen other templates to do the same thing, like this one

Use templates to get an array's size and end address

and I understand those, but I've been having difficulty with this one.

Any help would be appreciated.

解决方案

The function template is named ArraySizeHelper, for a function that takes one argument, a reference to a T [N], and returns a reference to a char [N].

The macro passes your object (let's say it's X obj[M]) as the argument. The compiler infers that T == X and N == M. So it declares a function with a return type of char (&)[M]. The macro then wraps this return value with sizeof, so it's really doing sizeof(char [M]), which is M.

If you give it a non-array type (e.g. a T *), then the template parameter inference will fail.

As @Alf points out below, the advantage of this hybrid template-macro system over the alternative template-only approach is that this gives you a compile-time constant.

这篇关于这个数组大小模板如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆