Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return correct type of data in templates?

#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?

like image 538
Rakshanda Meshram Avatar asked Jan 15 '20 17:01

Rakshanda Meshram


1 Answers

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.

like image 59
N. Shead Avatar answered Nov 14 '22 03:11

N. Shead