首页 文章

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

提问于
浏览
13

考虑这个 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'std :: cout << foo()之前使用'auto foo()'; ^

How do I forward-declare foo() here? 或者更合适, is it possible to forward-declare foo()?


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

发生了同样的错误 .

1 回答

  • 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
    }
    

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

相关问题