I am looking into template functions right now and found a question i have no answer for. Lets say i have a max function that compares two numbers and returns the bigger number. It should be possible to compare different types(int with double, double with int etc.). The function looks like this:
template <typename T, typename A>
A max(T a, A b) {
return (a>b) ? a: b;
}
Now when i call the function with max(2.5,1) it returns 2, since A is the return type and the double will be an int. If i change the return type to T, and call the function again it will return 2.5 which is what i want, but if i call max(1,2.5) it will return 2 again, but i want 2.5. Is there a way to always return the type of the bigger number, no matter the return type and the order of the numbers i typed in?
I tried different combinations, but couldnt figure out how to get my desired return type.
Actually, what you ask for literally does not make much sense because C++ is statically typed. Consider this:
int a = 0;
double b = 0.0;
std::cin >> a >> b;
?? x = max(a,b);
What type is x? You need to pick. At compile time. Hence you cannot return the type of the bigger of a and b. auto x does not help, because auto merely makes the compiler pick but it is not known wich is bigger before the user entered the numbers. What you can choose as return type is the common type of a and b.
You can use std::common_type:
#include <type_traits>
template <typename T, typename A>
std::common_type_t<T,A> max(T a, A b) {
return (a>b) ? a: b;
}
Though anyhow the conditional operator has that type so you can simply use auto:
template <typename T, typename A>
auto max(T a, A b) {
return (a>b) ? a: b;
}
Note that this will not auto-magically adjust the return type to either T or A depending on which value is bigger. It will return the type of the conditional operator and is effectively the same as the code with the std::common_type.
Live Demo
On the other hand, if a and b are known at compile time, then you can determine the type of the bigger value and use it:
template <auto a,auto b>
auto max() {
if constexpr(a > b) return a;
else return b;
}
int main() {
std::cout << max<1,2.5>(); // double non type template argument since c++20
}
Live Demo
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