Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General min and max - C++

Tags:

c++

c++11

Writing a general minimum function, Two questions came to my mind. The code works fine with any input type and different argument number:

namespace xyz
{

template <typename T1, typename T2>
auto min(const T1 &a, const T2 &b) -> decltype(a+b)
{
    return a < b ? a : b;
}

template <typename T1, typename T2, typename ... Args>
auto min(const T1 &a, const T2 &b, Args ... args) -> decltype(a+b)
{
    return min(min(a, b), args...);
}

}

int main()
{
    cout << xyz::min(4, 5.8f, 3, 1.8, 3, 1.1, 9) << endl;
    //                   ^        ^           ^
    //                   |        |           |
    //                 float    double       int
}

 

  • Is there a better replacement for decltype(a+b)? I thing there's a standard class which I can't remember, something like decltype(std::THE_RESULT<a,b>::type).

  • The returned type of that decltype(std::THE_RESULT<a,b>::type)is const & or not ?

like image 998
masoud Avatar asked May 11 '13 14:05

masoud


2 Answers

std::common_type(c++11):

For non-specialized std::common_type, the rules for determining the common type between every pair T1, T2 are exactly the rules for determining the return type of the ternary conditional operator where T1 and T2 are the types of its second and the third operands.

and

For arithmetic types, the common type may also be viewed as the type of the (possibly mixed-mode) arithmetic expression such as T0() + T1() + ... + Tn().

Not sure about const&, but you could play with std::remove_cv and std::remove_reference (and std::is_reference to find out the answer).

In fact, here's a list of type support utilities. Knock yourself out.

like image 116
BoBTFish Avatar answered Oct 17 '22 20:10

BoBTFish


After the answer and worth comments I did it as below:

template <typename T1, typename T2>
auto min(const T1 &a, const T2 &b) 
-> typename std::common_type<const T1&, const T2&>::type
{
    return a < b ? a : b;
}

template <typename T1, typename T2, typename ... Args>
auto min(const T1 &a, const T2 &b, const Args& ... args)
-> typename std::common_type<const T1&, const T2&, const Args& ...>::type
{
    return min(min(a, b), args...);
}
like image 41
masoud Avatar answered Oct 17 '22 21:10

masoud