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

Mar*_*cia 13 c++ auto c++14

考虑一下这个C++ 1y代码(LIVE EXAMPLE):

#include <iostream>

auto foo();

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

auto foo() {
    return 1234;
}
Run Code Online (Sandbox Code Playgroud)

编译器(GCC 4.8.1)慷慨地发现了这个错误:

main.cpp:在函数'int main()'中:
main.cpp:8:18:错误:在扣除'
auto'std :: cout << foo()之前使用'auto foo()'
                   ^

我如何foo()在这里转发声明?或者更恰当的说,是否有可能向前宣布foo()


我也尝试编译代码,我试图foo().h文件中声明,foo()就像.cpp文件中的上面一样,包含.h在我的main.cpp文件包含int main()和调用foo(),并构建它们.

发生了同样的错误.

Rap*_*ptz 17

根据N3638中提出的论文,它明确有效.

相关片段:

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
Run Code Online (Sandbox Code Playgroud)

然而它继续说:

如果需要具有未减少占位符类型的实体的类型来确定表达式的类型,则该程序是不正确的.但是一旦在函数中看到了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
}
Run Code Online (Sandbox Code Playgroud)

因此,在定义之前使用它的事实会导致错误.