General min and max - C ++

Having written a general minimal function, two questions occurred to me. The code works fine with any type of input and another 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 have a standard class there that I don’t remember, something like decltype(std::THE_RESULT<a,b>::type) .

  • The return type of this decltype(std::THE_RESULT<a,b>::type) is equal to const & or not?

+8
c ++ c ++ 11
May 11 '13 at 14:12
source share
2 answers

std::common_type ( c++11 ):

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

and

For arithmetic types, the general type can also be considered as the type of a (possibly mixed) arithmetic expression, such as T0() + T1() + ... + Tn().

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

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

+13
May 11 '13 at 14:17
source share

After the answer and comments, I did this as shown 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...); } 
+5
May 11 '13 at 14:49
source share



All Articles