简体   繁体   English

如何声明一个推导其返回类型的函数?

[英]How do I declare a function whose return type is deduced?

Consider this C++1y code ( LIVE EXAMPLE ): 考虑以下C ++ 1y代码( 实时示例 ):

#include <iostream>

auto foo();

int main() {
    std::cout << foo();   // ERROR!
}

auto foo() {
    return 1234;
}

The compiler (GCC 4.8.1) generously shoots out this error: 编译器(GCC 4.8.1)慷慨地排除了此错误:

main.cpp: In function 'int main()': main.cpp:在函数'int main()'中:
main.cpp:8:18: error: use of 'auto foo()' before deduction of 'auto' main.cpp:8:18:错误:在扣除'auto'之前使用'auto foo()'
std::cout << foo(); std :: cout << foo();
^ ^

How do I forward-declare foo() here? 我如何在这里转发声明foo() Or maybe more appropriately, is it possible to forward-declare foo() ? 或更恰当地说, 是否可以向前声明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. 我也试着编译代码,我想申报foo().h文件中定义foo()就像上面的一个.cpp文件,包括.h在我main.cpp文件包含int main()和对foo()的调用,并构建了它们。

The same error occurred. 发生相同的错误。

According to the paper it was proposed in, N3638 , it is explicitly valid to do so. 根据N3638中提出的论文 ,这样做显然是有效的。

Relevant snippet: 相关摘要:

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

However it goes on to say: 但是它继续说:

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. 但是,一旦在函数中看到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
}

So the fact that you used it before it was defined causes it to error. 因此,您在定义它之前就使用它的事实会导致它出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM