Search code examples
c++templatestypesgeneric-programming

Auto return value inference and c++ static typing


In this very interesting use case of auto return value inference(taken from: 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;
}

Wouldnt the type of the return value HAVE to be deduced at run-time because parameters a and b are not constant expressions that can be evaluated at compile-time? I mean, the return value would HAVE to be either A type or B type for every instantiated function call, but it is not clear in compile-time which one it is. a < b ? a : b is not a constant expression is it?

Wouldn`t this mean c++ is a dynamically typed language. If not, how is the return value of the function deduced at compile time? Are two functions created per instantiation, one that returns A type and another that returns B type? How would that work?


Solution

  • You'll get one function that returns a value of common type of A and B. C++ is a statically typed language, so the type of cond ? a : b should be known at compile time. There are special rules to determine that common type. Informally speaking, it is a type that A and B can be implicitly converted to. If no such type exists, you'll get a compilation error.

    For example,

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

    The type of c will always be double. If a is less than b, the return value will be a converted into double, as if static_cast<double>(a).