Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement generic max function?

Tags:

c++

templates

I know this is because the return type of the template function is same as that of the first argument (T).
How can I modify this template so that, it behaves correctly in all cases?

#include <iostream>
using namespace std;
template <typename T, typename U>
T max(T x, U y)
{
    return x>y ? x : y;
}

int main()
{
    cout<<max(17.9,17)<<"\n";
    cout<<max(17,17.9)<<"\n";
}

Output:

17.9  
17
like image 640
cppcoder Avatar asked Dec 01 '22 05:12

cppcoder


1 Answers

The behaviour for your implementation is correct, though you may not want that output. The problem with the return type in your code.

You may want to use trailing-return type if you can use C++11:

template <typename T, typename U>
auto max(T x, U y) -> decltype(x>y ? x : y)    //C++11 only
{
    return x>y ? x : y;
}

which would give this output:

17.9
17.9

I hope that is the desired output.

Online demo : http://ideone.com/2Sh5Y

like image 179
Nawaz Avatar answered Dec 04 '22 14:12

Nawaz