为什么“引用数组”在C ++中以这种令人困惑的方式定义? [英] Why is "reference to array" defined in such confusing way in C++?

查看:106
本文介绍了为什么“引用数组”在C ++中以这种令人困惑的方式定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是基于此处的摘录。我想要一个模板化的函数,该函数接受对实例化该函数时得出的大小数组的引用:

The following code is based on a snippet from here. I want a templated function that accepts a reference to an array of size that is deduced when the function is instantiated:

template<int size>
void myFunction( SomeType(&param)[size] )
{
    //use param and size here
}

//called like this:
SomeType array[SomeConstant];
myFunction( array ); //SomeConstant magically gets into the function as "size"

现在我对<$ c感到困惑$ c> SomeType(& param)[size] 。我希望以下各项可以正常工作:

Now I'm confused with SomeType(&param)[size]. I'd expect the following to work:

template<int size>
void myFunction( (SomeType[size])& param ) {}

但是

为什么我需要这样奇怪的语法来引用固定大小的数组?

Why do I need such weird syntax for "reference to array of fixed size"?

推荐答案

第二个声明的问题在于应使用哪个值作为标识符?它应该是 param ,还是 SomeType ?由于括号的原因,将首先解析声明的第一部分,但是如果是这样,并且 SomeType 不是标识符,那么在解析的那一点

The problem with your second declaration becomes what value should be used as the identifier? Should it be param, or should it be SomeType? Because of the parenthesis, the first part of the declaration would be parsed first, but if that's the case, and SomeType was not the identifier, then at what point in the parsing does the identifier get named?

使用顺时针解析模式 ,其中标识符是最里面未知的解析元素(例如,不是已知标记或关键字的东西……请参见链接),语法类似

Using the clockwise parsing pattern of C/C++, where the identifier is the the inner-most unknown parsed element (i.e., something that isn't a known token or keyword ... see the link), syntax like

(SomeType[size])& param

将读为 SomeType是一个固定的'size'数组,该数组是某些对象 param ,这当然没有任何意义,因为尚未使用数组的对象类型声明该数组。另一方面

would read "SomeType is an array of fixed 'size' that is a reference-type type for some object param" which of course doesn't make any sense since the array has not been declared with the type of object that it is an array of. On the otherhand

SomeType(&param)[size]

使用相同的解析规则将显示为 param 是对包含对象的固定大小数组的引用键入 SomeType 。后者当然是您想要的声明,并且对C / C ++解析器有意义。

using the same parsing rules would read "param is a reference to an array of fixed size that contains objects of type SomeType". The latter is of course the declaration you want, and what makes sense to the C/C++ parser.

这篇关于为什么“引用数组”在C ++中以这种令人困惑的方式定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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