Table 按值传递

Table pass by value

是否可以将原始 table 传递给值函数?我认为这是不可能的,但我正在寻找官方消息来源来证实这一点。


我知道如何通过 table 参考:

template<typename T, size_t N, size_t M>
void first_example(T (&table_in_function)[N][M]) {
  //...
 }
 //...
int a[50][20];
//...
first_example(a);

std::array,但令我难过的是,我正在寻找原始 table 的解决方案。简单的想法,去掉&,显然是错误的。我也不是在寻找类似的东西:

template<typename T, size_t N, size_t M>
void third_example(T (&temp_ref)[N][M]) {
  T local_table[N][M];
  //...
 }

我接受魔术代码和元编程等解决方案。

这是不可能的。当传递给函数时,C 风格的数组会自动衰减为指针。

您必须显式复制数组。

处理此 的规范方法是 使用 std::array (或等效的包装器类型)。

除此之外,你运气不好,因为 C++ 禁止数组的直接复制初始化:

[C++11: 8.5/16]: [..] The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly parenthesized) expression, the source type is not defined.

  • If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).
  • If the destination type is a reference type, see 8.5.3.
  • If the destination type is an array of characters, an array of char16_t, an array of char32_t, or an array of wchar_t, and the initializer is a string literal, see 8.5.2.
  • If the initializer is (), the object is value-initialized.
  • Otherwise, if the destination type is an array, the program is ill-formed. [..]

如您所知,您似乎可以将数组直接传递给函数的唯一原因是因为它们的名称实际上退化为指针(导致我称之为按句柄传递)。尽管在相应的使用语法中出现,但这在功能上与通过引用传递没有任何不同。

上面的引述意味着你可以做任何事情来解决数组名称衰减只会让你 运行 陷入更基本的问题,即数组可能无法直接复制。

无法声明数组类型的函数参数。特别是 C++ 标准 (§8.3.5/5) 指定:

After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively.

因此,如果您尝试创建一个接受数组类型参数的函数,该参数将被编译器 "adjusted" 变成一个指针。

同样,when/if您尝试将数组传递给函数,实际传递的是该数组第一个元素的地址。