函数 G++ 6.2 的自动类型推导

auto type deduction for function g++ 6.2

本文关键字:类型 G++ 函数      更新时间:2023-10-16

我正在试验现代C++'auto',发现了一个简单的示例,它会产生错误,我不明白为什么:

主.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"。 感谢您的建议。

返回类型推导根本无法用于声明。编译器使用定义(实现)通过检查函数实际返回的内容来推断类型。在声明中不可能这样做,因此当您调用函数时编译将失败,因为还没有推导的返回类型。

使用尾随返回类型时,可以显式指定返回类型。在您的情况下,这与使用旧的"正常"方式声明返回类型没有什么不同。