0

Can someone explain to me why the following code gives an error?

#include <iostream>
using namespace std;

template <typename aa, typename bb>
auto minimum(aa a, bb b)
{
        if (a < b) return a;
        else return b;
}

int main()
{
    cout << minimum(7, 5.1);
}

inconsistent deduction for 'auto': 'int' and then 'double'

Why does this code work without error?

#include <iostream>
using namespace std;

template <typename aa, typename bb>
auto minimum(aa a, bb b)
{
     return a < b ? a : b;    
}

int main()
{
    cout << minimum(7, 5.1);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Mirel
  • 9
  • 1
  • 2
  • For deduction with more than one return statement to work, types in all return statements must match. There's no automatic promotion to the common type or anything like that. OTOH in a ternary operator there is an automatic conversion of tge two branches to the common type before any deductiin has a chance to happen. – n. m. could be an AI Mar 11 '18 at 16:57

2 Answers2

2

Somebody smarter than me can cite the relevant part of the standard, but the short version is that the ternary operator works differently than if/else. With the first example (if/else), you have two distinct returns, and you're potentially returning different types (you do this in your example). The function has to return a single type, so it doesn't know which is correct (i.e., whether to promote int to double or degrade double to int).

In your second example, the ternary operator can figure out the appropriate type based on the arguments (specially the latter two). In your example, it will always treat the result as double, so your function knows that's what it needs to return.

Stephen Newell
  • 7,330
  • 1
  • 24
  • 28
2

In the first case, you have 2 separate return statements returning different data types, as a is an int and b is a double, so the auto doesn't know which data type to deduce.

In the second case, the result of the ?: operator is 1 specific data type, and there is only 1 return statement, so there is no confusion for auto to know which data type to deduce.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770