C++ 类型推断递归函数

c++ type inference recursive functions

试图理解为什么类型推导在此处使用条件运算符失败。
在这种情况下,标准中的某些内容试图防止类型推导?任何理解这一点的指示都会很棒。

auto mfact(int i)
{
    return (0==i) ? 1 : i * mfact(i-1);
}

auto mfact2(int i)
{
    if (0 == i)
        return 1;

    else
        return i * mfact2(i-1);
}
error: use of ‘auto mfact(int)’ before deduction of ‘auto’    
    return (0==i) ? 1 : i * mfact(i-1);

mfact中的问题是三元运算符。该运算符的语义指定表达式的类型是两个条件子表达式的公共类型(我解释了一下)。

常见的类型是什么?为什么它是 int 并且...还有待推导的类型。
啊,没问题!要推导的类型是什么?这是三元运算符的类型...

我们有先有鸡还是先有蛋的问题。整个函数定义格式错误,因为无法确定表达式的类型。

mfact2呢?它有两个单独的 return 语句。第一个是普通整数。由于一个函数只能有一个 return 类型,return 类型推导要求两个 return return 语句不冲突。

引用C++14标准修订版:

[dcl.spec.auto/2]

The placeholder type can appear with a function declarator in the decl-specifier-seq, type-specifier-seq, conversion-function-id, or trailing-return-type, in any context where such a declarator is valid. If the function declarator includes a trailing-return-type ([dcl.fct]), that specifies the declared return type of the function. If the declared return type of the function contains a placeholder type, the return type of the function is deduced from return statements in the body of the function, if any.

所以一个 return 语句来推断类型就足够了,并且:

[dcl.spec.auto/9]

If a function with a declared return type that contains a placeholder type has multiple return statements, the return type is deduced for each return statement. If the type deduced is not the same in each deduction, the program is ill-formed.

在这个简单的例子中,第一个语句要求它是 int,第二个包含递归调用。由于同一个函数重载只能有一个 return 类型,因此递归调用也必须是 int 类型。两个 return 说法一致。