简体   繁体   English

如何通过引用未知大小的数组来调用函数?

[英]How to call a function with a reference to an unknown size array?

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: 现在它是有效的(在Apple clang 3.0版上测试)来定义这样的功能:

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. 注意到int[]int[n]是不同的类型,通常是不兼容的。

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? 为什么应该使用void by_reference(int (*&array), int size)

Your assumption is wrong, the program is ill-formed. 你的假设是错误的,程序是不正确的。 See C++11 standard 8.3.5/8: 请参阅C ++ 11标准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. 如果参数的类型包括“指向T的未知边界的数组的指针”或“对T的未知边界的数组的引用”形式的类型,则该程序是错误的。

clang allows this as a compiler extension. clang允许这作为编译器扩展。 g++, for example, will not accept it. 例如,g ++不会接受它。

You can however use templates to deduce the size of the passed array: 但是,您可以使用模板来推断传递的数组的大小:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM