简体   繁体   中英

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

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;
}

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM