Function auto return type | Sololearn: Learn to code for FREE!
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; }

6th Jun 2020, 8:43 AM
Uros Zivkovic
Uros Zivkovic - avatar
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
6th Jun 2020, 9:35 AM
Bobby Fischer
Bobby Fischer - avatar