New course! Every coder should learn Generative AI!
Try a free lesson+ 2
Function auto return type
Why does it work with ternary operator but not with classic if approach? template <class T, class F> auto smaller(T a, F b) { return(a<b ? a:b); //this works if(a<b) //this does not return a; // Error: else // inconsistent deduction return b; // for auto return type } int main(void) { cout << smaller(4,5.2) << endl; cout << smaller(6,5.2) << endl; return 0; }
1 Answer
+ 1
It works with ternary operator because a and b are implicitly converted into the common arithmetic type. There are rules for second operands and third operands conversion, you can read here:
https://docs.microsoft.com/en-us/cpp/cpp/conditional-operator-q?view=vs-2019