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

15

考虑以下 C++1y 代码 (实时示例):

#include <iostream>

auto foo();

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

auto foo() {
    return 1234;
}
编译器(GCC 4.8.1)友善地报告了这个错误:
main.cpp: In function ‘int main()’: main.cpp:8:18: error: 在推断‘auto’前使用了‘auto foo()’ std::cout << foo(); ^ 如何在此处前向声明foo()?或者更适当的是,是否可以前向声明foo()?
我还尝试编译了一些代码,在.h文件中尝试声明foo(),在.cpp文件中像上面那样定义foo(),在main.cpp文件中包含.h文件,其中包含int main()和对foo()的调用,然后构建它们。
出现了相同的错误。

你确定你真的需要那个吗?我认为创建返回值如此不明确的函数通常不是一个好主意,也许你需要返回某个抽象高级类的实例?如果你知道你在做什么,就不要介意我的话 :) - SpongeBobFan
1个回答

19
根据提出该建议的文件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

然而,它继续说:

如果需要确定表达式类型而实体类型具有未推导的占位符类型,则程序是非法的。但是,一旦在函数中看到了返回语句,从该语句推导出的返回类型可以在函数的其余部分中使用,包括其他返回语句。

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
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接