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

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

问题描述

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

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

但是,出现以下错误.

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?

推荐答案

这是 [dcl.spec.auto/11] :

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

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
}

-示例]

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

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天全站免登陆