如何调用与一个未知大小的数组的引用的功能? [英] How to call a function with a reference to an unknown size array?

查看:150
本文介绍了如何调用与一个未知大小的数组的引用的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个有效的code:

 模板<为size_t大小>
无效by_numbered_reference(INT(安培;数组)[大小]);

这个函数接受数组作为参数,编译器可以使用模板参数推导演绎出它的大小。

现在它是有效的(苹果铿锵3.0版测试)来定义这样的功能:

 无效by_reference(INT(安培;数组)[],INT大小);

哪个(应该)接受未知大小的数组作为参数的参考。注意到 INT [] 的INT [n] 是不同的类型,一般是不相容的。

我发现如何调用该函数的唯一方法是:

 为int *阵列;
by_reference(reinter pret_cast&下; INT(安培)[]≥(*阵列),ARRAY_SIZE);


  1. 为什么语言接受未知大小的数组作为一个有效的函数参数的引用,同时有定义这样的变量没有直接的方法是什么?

  2. 是否有哪里需要此语法任何已知的用例?

  3. 为什么无效by_reference(INT(*&安培;数组),INT大小)?应的不可以来代替


解决方案

您的假设是错误的,是非法的构造方案。见C ++ 11标准8.3.5 / 8:


  

如果一个参数的类型包括一种形式的指针来约束的T未知的数组或参考
  开往的T未知的数组,该计划是非法的构造。


铛允许此作为编译器的扩展。 G ++,例如,不会接受它。

但是,您可以使用模板来推断传递的数组的大小:

 模板<的std ::为size_t N'GT;
空隙by_reference(中间体(安培)[N])
{
    // 随你
}

Consider a valid code:

template<size_t size>
void by_numbered_reference(int (&array)[size]);

This function accepts an array as an argument and compiler can deduce the size of it using template argument deduction.

Now it is valid (tested on Apple clang version 3.0) to define such function:

void by_reference(int (&array)[], int size);

Which (should) accept a reference to an unknown size array as an argument. Noting that int[] and int[n] are distinct types and generally are incompatible.

The only way which I found how to invoke this function is:

int * array;
by_reference(reinterpret_cast<int(&)[]>(*array), array_size);

  1. Why does the language accept a reference to an unknown size array as a valid function argument, while there is no straightforward way to define such variable?
  2. Are there any known use cases where this syntax is required?
  3. Why void by_reference(int (*&array), int size) should not be used instead?

解决方案

Your assumption is wrong, the program is ill-formed. See C++11 standard 8.3.5/8:

If the type of a parameter includes a type of the form "pointer to array of unknown bound of T" or "reference to array of unknown bound of T," the program is ill-formed.

clang allows this as a compiler extension. g++, for example, will not accept it.

You can however use templates to deduce the size of the passed array:

template <std::size_t N>
void by_reference(int (&)[N])
{
    // whatever
}

这篇关于如何调用与一个未知大小的数组的引用的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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