gpt4 book ai didi

c++ - 从用 decltype(auto) 声明的函数返回一个数组?

转载 作者:行者123 更新时间:2023-12-04 16:37:08 25 4
gpt4 key购买 nike

我想从函数返回一个数组(或对数组的引用),如下所示:

decltype(auto) bar() { static int a[2]; return a; }
不幸的是,它会导致非常神秘的错误。海湾合作委员会提示:
error: cannot convert 'int [2]' to 'int [2]' in return
而 Clang 在解释这个问题时也不是更好:
error: array initializer must be an initializer list
演示: https://gcc.godbolt.org/z/ao7Txa9oP
甚至可以从函数返回数组吗? (我可以摆脱 decltype(auto) 。)
如果不是,那么为什么,只要函数可以以各种方式接受数组,例如:
void f(auto [2]);
void f(auto (&)[2]);

最佳答案

问题确实是decltype(auto) .返回类型是通过以下列表推导出来的(所讨论的表达式是给 return 语句的表达式):

[dcl.type.decltype] (redacted for emphasis)

decltype-specifier:
decltype ( expression )

1 For an expression E, the type denoted by decltype(E) is definedas follows:

  • ...
  • ...
  • otherwise, if E is an unparenthesized id-expression or an unparenthesized class member access ([expr.ref]), decltype(E) is thetype of the entity named by E. If there is no such entity, or if Enames a set of overloaded functions, the program is ill-formed;
  • ...
  • ...
a的类型是 int[2] .所以你本质上是在定义一个具有数组返回类型的函数......但是......

[dcl.fct]

11 Functions shall not have a return type of type array orfunction, although they may have a return type of type pointer orreference to such things. There shall be no arrays of functions,although there can be arrays of pointers to functions.


您无意中生成了格式错误的函数类型。所以是的,正如您所指出的,解决方案是不使用 decltype .您可以显式返回一个引用(到推导的数组类型),因为这确实是您想要的:
auto& bar() { static int a[2]; return a; }
或者如果你想明确返回类型,而不进入声明者 hell ,你可以以尾随方式指定它:
auto bar() -> int(&)[2] { static int a[2]; return a; }
无论哪种方式,我都会说这比依赖 decltype 的(有时是神秘的)语义要好.当您显式返回左值引用时(当这是您的全部意图时)没有细微的错误。

顺便说一句,您的最后一个问题包含尚未指定为合法的声明(尽管已被实现接受,因为它们应该是一致的)。这是 CWG Issue 2397 .但它的要点是它的行为就像人们期望函数参数中的数组类型一样。 auto [2]调整为 auto* , 而 auto(&) [2]只绑定(bind)到特定类型的数组。这是一个缩写的函数模板,相当于:
template<typename T>
void f(T[2]);

template<typename T>
void f(T(&)[2]);
返回类型不会像参数那样进行调整。其中参数类型调整本身是 C 传承的东西,从中我们得到了不是一等公民的原始数组。随着类型的发展,它们非常不规则。如果你需要“更清晰”的数组值语义,你有 std::array正是为了这个目的。

关于c++ - 从用 decltype(auto) 声明的函数返回一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68509535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com