如何声明一个推导出返回类型的函数? [英] How do I declare a function whose return type is deduced?

查看:32
本文介绍了如何声明一个推导出返回类型的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下这个 C++1y 代码 (noreloferb"现场示例):

Consider this C++1y code (LIVE EXAMPLE):

#include <iostream>

auto foo();

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

auto foo() {
    return 1234;
}

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

The compiler (GCC 4.8.1) generously shoots out this error:

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

main.cpp: In function ‘int main()’:
main.cpp:8:18: error: use of ‘auto foo()’ before deduction of ‘auto’
std::cout << foo();
                   ^

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

How do I forward-declare foo() here? Or maybe more appropriately, is it possible to forward-declare foo()?

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

I've also tried compiling code where I tried to declare foo() in the .h file, defined foo() just like the one above in a .cpp file, included the .h in my main.cpp file containing int main() and the call to foo(), and built them.

出现同样的错误.

推荐答案

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

According to the paper it was proposed in, N3638, it is explicitly valid to do so.

相关片段:

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 语句.

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed. But once a return statement has been seen in a function, the return type deduced from that statement can be used in the rest of the function, including in other return statements.

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
}

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

So the fact that you used it before it was defined causes it to error.

这篇关于如何声明一个推导出返回类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆