如何声明一个返回类型被推导的函数? [英] How do I declare a function whose return type is deduced?
问题描述
请考虑此 C ++ 1y 代码( LIVE示例) ):
Consider this C++1y code (LIVE EXAMPLE):
#include <iostream>
auto foo();
int main() {
std::cout << foo(); // ERROR!
}
auto foo() {
return 1234;
}
编译器(GCC 4.8.1) p>
The compiler (GCC 4.8.1) generously shoots out this error:
main.cpp:在函数'int main()'中:
main.cpp:8:18:在扣除'auto'之前使用'auto foo()'
std :: cout< foo();
main.cpp: In function ‘int main()’:
main.cpp:8:18: error: use of ‘auto foo()’ before deduction of ‘auto’
std::cout << foo();
^
如何转发声明 foo()
或者更合适的是,可以转发声明 foo()
?
How do I forward-declare foo()
here? Or maybe more appropriately, is it possible to forward-declare foo()
?
我也试过编译代码,我试图在<$ c $中声明 foo()
c> .h 文件,定义 foo()
,就像上面的 .cpp
文件,包含 .h
在我的 main.cpp
文件包含 int main )
和对 foo()
的调用,并构建它们。
I've also tried compiling code where I tried to declare foo()
in the .h
file, defined foo()
just like the one above in a .cpp
file, included the .h
in my main.cpp
file containing int main()
and the call to foo()
, and built them.
错误。
推荐答案
根据提出的文件, N3638 ,它显然有效。
According to the paper it was proposed in, N3638, it is explicitly valid to do so.
相关片段:
[ Example:
auto x = 5; // OK: x has type int
const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int
static auto y = 0.0; // OK: y has type double
auto int r; // error: auto is not a storage-class-specifier
auto f() -> int; // OK: f returns int
auto g() { return 0.0; } // OK: g returns double
auto h(); // OK, h's return type will be deduced when it is defined
— end example ]
但是它继续说:
如果需要具有未减少的占位符类型的实体类型来确定表达式的类型,程序是不成形的。但是一旦在函数中看到返回语句,从该语句推导出的返回类型可以在函数的其余部分中使用,包括在其他返回语句中。
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. But once a return statement has been seen in a function, 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]
因此,你在定义之前使用它的事实导致它的错误。
So the fact that you used it before it was defined causes it to error.
这篇关于如何声明一个返回类型被推导的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!