gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:58:56 25 4
gpt4 key购买 nike

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

#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: use of ‘auto foo()’ before deduction of ‘auto’
std::cout << foo();
                   ^

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


我也尝试过编译代码,我试图在 .h 文件中声明 foo(),定义 foo() 只是与 .cpp 文件中的上述类似,在我的 main.cpp 文件中包含 .h,其中包含 int main() 和对 foo() 的调用,并构建它们。

发生了同样的错误。

最佳答案

根据提出的论文,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

但它继续说:

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
}

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

关于c++ - 如何声明一个推导出返回类型的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17268974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com