msc*_*msc 24 c++ gcc function auto c++14
我在GCC中编译了以下程序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;
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误.
Run Code Online (Sandbox Code Playgroud)In function 'int main()': 8:16: error: use of 'auto func(int)' before deduction of 'auto' auto ret = func(5);
那么,我在这里错过了什么?
Gri*_*wes 34
如果需要具有未减少占位符类型的实体的类型来确定表达式的类型,则该程序是不正确的.但是,一旦在函数中看到了非丢弃的return语句,从该语句推导出的返回类型可以在函数的其余部分中使用,包括在其他return语句中.[例如:
Run Code Online (Sandbox Code Playgroud)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
使用的情况下,这通常通过在使用点之前移动定义来实现.如果您实际上不需要使用返回类型推导,则可以在使用后保留定义,如果您在声明中提供签名(包括返回类型).
Bar*_*icz 27
Clang有一个更好的错误信息:
main.cpp:8:16: error: function 'func' with deduced return type cannot be used before it is defined
auto ret = func(5);
^
Run Code Online (Sandbox Code Playgroud)
我猜这是不言自明的.
如果auto
在不使用尾部返回类型语法的函数声明中用作返回类型,则该关键字auto
指示将从其return语句的操作数推导出返回类型.这意味着在函数定义之前不能执行推导func()
,但在此之前它已被使用main()
.
您可以在之前移动定义main()
,或使用尾随返回类型语法在声明上指定返回类型.
归档时间: |
|
查看次数: |
9441 次 |
最近记录: |