C++泛型函数的灵活性

Bra*_*art 2 c++ templates

我想制作灵活的通用函数,它的返回可以处理多个未知类型.

#include <iostream>

template<typename U, typename V>
U Max(U arg1, V arg2) {
    return arg1 > arg2 ? arg1 : arg2;
}

using namespace std;
int main()
{
    double x = 9.88;
    int  n = 8;
    cout << Max(x, n) << endl; // output is 9.88
    int z = 4;
    double r = 5.88;
    // output is 5 not 5.88, I want to code one function deal with all types.
    cout << Max(z, r) << endl; 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 6

你可以用std::common_type,

template<typename U,typename V>
typename std::common_type<U, V>::type 
Max(U arg1, V arg2){
    return arg1 > arg2 ? arg1 : arg2;
}
Run Code Online (Sandbox Code Playgroud)