What should be the return type of the following function template with multiple parameters?

Viewed 69

What should be the return type of the following function template-

#include<iostream>
using namespace std;

template <class T1, class T2>
returntype biggerNum(T1 num1 , T2 num2){
    if(num1>num2)
        return num1;
    return num2;
}

int main(){
    cout<<biggerNum(2,3.4);
    return 0;
}
2 Answers

Since both types will need to be convertible to some common type, you can use std::common_type to get the common type between T1 and T2 like

template <class T1, class T2>
std::common_type_t<T1, T2> biggerNum(T1 num1 , T2 num2){
    if(num1>num2)
        return num1;
    return num2;
}

If there is no such type, then you will get a compiler error.

A solution mentioned in the comments is to force the parameters to be only one type:

template <class T>
T biggerNum(T num1, T num2){
    if(num1>num2)
        return num1;
    return num2;
}

This would force the conversion on the user side, like std::min and std::max:

float a = 9;
int b = 8;
biggerNum(a, static_cast<float>(b));
Related