在 C 14 中扣除 'auto' 之前使用 'auto func(int)'

新手上路,请多包涵

我使用 C++14 在 GCC 中编译了以下程序。

 #include <iostream>
using namespace std;

auto func(int i);

int main()
{
    auto ret = func(5);
    return 0;
}

auto func(int i)
{
  if (i == 1)
    return i;
  else
    return func(i-1) + i;
}

但是,我收到以下错误。

 In function 'int main()': 8:16: error: use of 'auto func(int)' before
deduction of 'auto'
 auto ret = func(5);

那么,我在这里缺少什么?

原文由 msc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

这是 [dcl.spec.auto/11]

如果需要具有未推导的占位符类型的实体的类型来确定表达式的类型,则程序是非良构的。但是,一旦在函数中看到了未丢弃的 return 语句,从该语句推导出的返回类型就可以在函数的其余部分中使用,包括在其他 return 语句中。 [ 例子:

 auto n = n;                     // error, n's type is unknown
auto f();
void g() { &f; }                // error, f's return type is unknown
auto sum(int i) {
  if (i == 1)
    return i;                   // sum's return type is int
  else
    return sum(i-1)+i;          // OK, sum's return type has been deduced
}

—结束示例]

要将其翻译成英文:编译器需要知道返回类型才能使用该函数。在 auto 这样使用的情况下,这通常是通过在使用点之前移动定义来实现的。如果您实际上不需要使用返回类型推导,如果您在声明中提供签名,包括返回类型,则可以保留使用后的定义。

原文由 Griwes 发布,翻译遵循 CC BY-SA 4.0 许可协议

Clang 有一个更好的错误信息:

 main.cpp:8:16: error: function 'func' with deduced return type cannot be used before it is defined
    auto ret = func(5);
               ^

我想这是不言自明的。

原文由 Bartek Banachewicz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题