自动 return 值推断和 C++ 静态类型

Auto return value inference and c++ static typing

在这个非常有趣的自动 return 值推断用例中(取自:https://www.geeksforgeeks.org/type-inference-in-c-auto-and-decltype/):

// A generic function which finds minimum of two values 
// return type is type of variable which is minimum 
template <class A, class B>
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
    return (a < b) ? a : b;
}

return 值的类型是否必须在 运行 时推导,因为参数 a 和 b 不是可以在编译时求值的常量表达式?我的意思是,对于每个实例化的函数调用,return 值必须是 A 类型或 B 类型,但在 compile-time 中并不清楚它是哪一个。 a < b ? a : b 不是常量表达式吗?

这是否意味着 C++ 是一种动态类型的语言。如果不是,函数的 return 值是如何在编译时推导出来的?每个实例化是否创建了两个函数,一个是 returns A 类型,另一个是 returns B 类型?那将如何运作?

您将获得一个函数,该函数 return 是 AB 的常见类型的值。 C++ 是一种静态类型语言,所以 cond ? a : b 的类型应该在编译时就知道了。有 special rules 来确定那个普通类型。通俗地说,就是AB可以隐式转换成的类型。如果不存在这样的类型,你会得到一个编译错误。

例如,

int    a = 1;
double b = 2;
auto   c = findMin(a, b);

c 的类型将始终为 double。如果 a 小于 b,return 值将被 a 转换为 double,就好像 static_cast<double>(a).