Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded function evaluated with ternary

Tags:

c++

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;
}
like image 347
Benoît Vernier Avatar asked Dec 25 '14 22:12

Benoît Vernier


People also ask

Can ternary operators be overloaded?

One is that although it's technically an operator, the ternary operator is devoted primarily to flow control, so overloading it would be more like overloading if or while than it is like overloading most other operators.

Does C++ provide any ternary operator if yes explain its working?

Since the Conditional Operator '?:' takes three operands to work, hence they are also called ternary operators. Working: Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then Expression2 will be executed and the result will be returned.

Is there ternary operator in C++?

In C++, the ternary operator (also known as the conditional operator) can be used to replace if...else in certain scenarios.

Which is an example of a ternary operator?

Example: C Ternary Operator Here, age >= 18 - test condition that checks if input value is greater or equal to 18. printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.


1 Answers

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.

like image 67
Anonymous Avatar answered Oct 30 '22 01:10

Anonymous