Generic min/max with variable argument count

suggest change

It’s possible to write a generic function (for example min) which accepts various numerical types and an arbitrary number of arguments. This function declares a min for two arguments and recurses for more. std::common_type is C++11. The trait is given the argument types themselves, not references to the parameters, so the return type is not a reference into the function.

template <typename T1, typename T2>
auto min(const T1 &a, const T2 &b) 
-> typename std::common_type<T1, 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<T1, T2, Args...>::type
{
    return min(min(a, b), args...);
}

auto minimum = min(4, 5.8f, 3, 1.8, 3, 1.1, 9); // common type is double

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents