【发布时间】:2015-02-13 11:10:23
【问题描述】:
我刚刚阅读了有关 C++14 中可用的名为“返回类型推导”的新功能,我对该类型的函数中的递归有疑问。我了解到该函数中的第一个返回必须允许推断返回类型。
Wiki 提供的示例完全符合该规则。
auto Correct(int i) {
if (i == 1)
return i; // return type deduced as int
else
return Correct(i-1)+i; // ok to call it now
}
auto Wrong(int i) {
if (i != 1)
return Wrong(i-1)+i; // Too soon to call this. No prior return statement.
else
return i; // return type deduced as int
}
我的问题是:
为什么当我将Wrong(int i) 更改为Wrong(auto i) 时,Wrong 函数开始编译?这个小小的变化背后隐藏着什么?
【问题讨论】:
-
基本上,你把
Wrong变成了一个函数模板。 -
auto作为常规函数中的参数是 GCC 扩展,而不是标准 C++14。 -
如果将
auto i更改为常规模板函数(template <typename T> auto Wrong(T i)),则会再次被拒绝。