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

时间:2013-06-24 06:08:59

标签: c++ auto c++14

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

#include <iostream>

auto foo();

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

auto foo() {
    return 1234;
}

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

  

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

如何在此向前声明foo()或者更合适,是否可以转发声明foo()


我还尝试编译代码,我尝试在foo()文件中声明.h,定义foo(),就像上面.cpp文件中的.h一样我的main.cpp文件中包含int main()的{​​{1}}和foo()的调用,并构建了它们。

发生了同样的错误。

1 个答案:

答案 0 :(得分: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

然而它继续说:

  

如果需要具有未减弱占位符类型的实体类型来确定表达式的类型,则程序格式错误。但是一旦在函数中看到了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
}

因此,在定义之前使用它会导致错误。

相关问题