递归函数中的返回类型推导 [英] Return type deduction in recursive function

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

问题描述

以下代码编译

auto foo(int i) {
  if( i == 1 )
    return i;
  else 
    return foo(i-1)+i ; 
}

跟随没有 c ++ 1y

While following doesn't, c++1y

auto foo(int i) {
  return (i == 1) ? i : foo(i-1)+i ;  
}






为什么不能编译推导第二种情况下的返回类型?我在这想念什么吗?


Why can't compiler deduce the return type in second case ? Am I missing something over here ?

在第二种情况下,我知道(i == 1)之后有一个序列点,但这不应该会影响编译,对吗?

I know there's a sequence point after (i == 1) in second scenario, but that shouldn't be affecting compilation, right ?

推荐答案

由于此规则,第一个有效,即最新草案

The first works because of this rule, 7.1.6.4/11 of the latest draft


在函数中可以看到c $ c> return 语句,但是从该语句推导的返回类型
可以在函数的其余部分中使用,包括在其他<$ c $中c> return 语句。

Once a return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements.

因此,将返回类型推导为 int 从第一个 return 语句开始;只需检查第二个,以确保它也给出 int ,并假定递归调用确实给出了。

So the return type is deduced as int from the first return statement; the second is just checked to make sure that it also gives int, assuming that the recursive call does.

第二个不编译,因为表达式的类型取决于返回类型;因此无法推断出类型。

The second doesn't compile because the type of the expression depends on the return type; so the type can't be deduced.

这篇关于递归函数中的返回类型推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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