我正在试验现代 C++“auto”并发现一个产生错误的简单示例,我不明白为什么:
main.cpp
// error: use of ‘auto test(int)’ before deduction of ‘auto’ int i = test(5);
int i = test(5);
测试.h
auto test(int i);
测试.cpp
auto test(int i) {
if (i == 1)
return i; // return type deduced as int
else
return Correct(i-1)+i; // ok to call it now
}
但是,如果我使用“->”指定类型,代码将构建并运行良好。例如:
auto test(int i) -> int;
g++ 6.2 是编译器的现代版本,我想知道为什么我必须使用“-> int”。感谢您的建议。
最佳答案
返回类型推导根本无法用于声明。编译器使用定义(实现)通过检查函数实际返回的内容来推断类型。在声明中不可能这样做,因此当您调用该函数时编译将失败,因为还没有推导出的返回类型。
当您使用尾随返回类型时,您明确指定了返回类型。在您的情况下,这与使用声明返回类型的旧“正常”方式没有什么不同。
关于c++ - 函数 g++ 6.2 的自动类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41617005/