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;
}
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.
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.
In C++, the ternary operator (also known as the conditional operator) can be used to replace if...else in certain scenarios.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With