#include <iostream>
using namespace std;
template <class X, class Y>
Y big(X a, Y b)
{
if (a > b)
return (a);
else return (b);
}
int main()
{
cout << big(32.8, 9);
}
Here I am using templates in CPP, so when I call the function big
bypassing arguments of double
and int
type, I want the return answer which is double
. The type here, it returns 32
instead of 32.8
.
How I get my desired output?
How to write a proper return type of big
function?
This is not the correct solution for your precise situation, in all likelihood – the other answers are likely to be much closer to what you want.
However, if you really need to return entirely different types at runtime for some reason, the correct solution (since c++17) is to use a std::variant
, which is a sort of type-safe union.
#include <variant>
template <typename X, typename Y>
std::variant<X, Y> max(X a, Y b) {
if (a > b)
return std::variant<X, Y>(std::in_place_index_t<0>, a);
else
return std::variant<X, Y>(std::in_place_index_t<1>, b);
}
Note that then the onus is on the caller to deal with the returned value, most likely using std::visit
or the like.
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