5

I have an overloaded function which can take two argument types : int and double. When I evaluate it with a ternary which can return either an int or a double, it always uses the double version. Why is that?

#include<iostream>
using namespace std;

void f(int a)
{
    cout << "int" << endl;
}

void f(double a)
{
    cout << "double" << endl;
}

int main()
{
    string a;
    cin >> a;
    f(a=="int" ? 3 : 3.14159);
    return 0;
}

1 Answers1

8

Ternary operator always do type promotion (into single type). So if one result is int and another is double, the result of ? operartor will always be double.

Anonymous
  • 2,122
  • 19
  • 26