在 C++14 中扣除“auto"之前使用“auto func(int)" [英] Use of 'auto func(int)' before deduction of 'auto' in C++14

查看:43
本文介绍了在 C++14 中扣除“auto"之前使用“auto func(int)"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#include 使用命名空间标准;自动功能(int i);int main(){自动 ret = func(5);返回0;}自动功能(int i){如果(我== 1)返回我;别的返回 func(i-1) + i;}

但是,我收到以下错误.

<块引用>

在函数int main()"中:8:16:错误:之前使用过auto func(int)"扣除汽车"自动 ret = func(5);

那么,我在这里错过了什么?

解决方案

This is [dcl.spec.auto/11]:

<块引用>

如果需要未推导占位符类型的实体类型为了确定表达式的类型,程序格式错误.一旦在函数中看到非丢弃的 return 语句,但是,从该语句推导出的返回类型可以用于函数的其余部分,包括在其他 return 语句中.[ 示例:

auto n = n;//错误,n 的类型未知自动 f();void g() { &f;}//错误,f 的返回类型未知自动求和(int i){如果(我== 1)返回我;//sum 的返回类型是 int别的返回 sum(i-1)+i;//OK,sum的返回类型已经推导出来}

— 结束示例 ]

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

I have compiled following program in GCC using C++14.

#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;  
}

But, I get the following error.

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

So, what am I missing here?

解决方案

This is [dcl.spec.auto/11]:

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed. Once a non-discarded return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements. [ Example:

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
}

 — end example ]

To translate this into English: the compiler needs to know the return type before you can use the function. In case of auto used like this, this is typically achieved by moving the definition before the point of use. If you don't actually need to use return type deduction, you can keep the definition after the use if you provide a signature, including the return type, in the declaration.

这篇关于在 C++14 中扣除“auto"之前使用“auto func(int)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆