【问题标题】:How do I declare a function whose return type is deduced?如何声明一个推导出返回类型的函数?
【发布时间】:2013-06-20 13:49:35
【问题描述】:

考虑一下这个 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 ^

我如何在这里转发声明foo()或者更恰当地说,是否可以转发声明foo()


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

发生了同样的错误。

【问题讨论】:

  • 你确定你真的需要那个吗?我认为创建返回如此未定义的函数的函数通常不是一个好主意,也许您需要返回一些抽象高级类的实例?如果你知道你在做什么,没有冒犯:)

标签: c++ auto c++14


【解决方案1】:

根据N3638 中提出的论文,这样做是明确有效的。

相关sn-p:

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
}

因此,您在定义之前使用它的事实会导致它出错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多