如何使用对未知大小数组的引用调用函数?

时间:2022-05-04 21:27:39

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:

现在它是有效的(在苹果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. 为什么语言接受对未知大小数组的引用作为有效的函数参数,而没有直接的方法来定义此类变量?
  3. Are there any known use cases where this syntax is required?
  4. 是否存在需要使用这种语法的已知用例?
  5. Why void by_reference(int (*&array), int size) should not be used instead?
  6. 为什么不应该使用void by_reference(int (*&array), int size) ?

1 个解决方案

#1


6  

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

你的假设是错误的,这个计划是错误的。看到c++标准8.3.5/8:11

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. g++, for example, will not accept it.

clang允许将其作为编译器扩展。例如,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
}

#1


6  

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

你的假设是错误的,这个计划是错误的。看到c++标准8.3.5/8:11

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. g++, for example, will not accept it.

clang允许将其作为编译器扩展。例如,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
}