I need reflections on my implementations of the C++11 variadic versions of std::min, std::max. Here are my two alternatives for std::min, where std::max is implemented analogously by just replacing std::min with std::max:
/*! Multi-Type Minimum of \p a. */
template <LessThanComparable T> const T & multi_type_min (const T & a) { return a; } // template termination
/*! Multi-Type Minimum of \p a and \p args. */
template <class T, class ... R >
//requires SameType <T , Args >...
T multi_type_min(const T & a, const R &... b)
{
return std::min(a, multi_type_min(b...));
}
/*! Minimum of \p a. */
template <LessThanComparable T> const T & common_type_min(const T & a) { return a; } // template termination
/*! Minimum of \p a and \p args. */
template <class T, class ... R, class C = typename boost::common_type<T, R...>::type >
C common_type_min(const T & a, const R &... b)
{
return std::min(static_cast<C>(a), static_cast<C>(common_type_min(b...)));
}
The key question is if we need common_type_min at all? Note that this allows min() to be called with one arguments. Could this cause confusions or problems?
Can’t you just write it such that it recurses until you stop at two parameters?
Here’s a (untested) snippet:
I’m guessing the
common_type_minvariant is necessary when there are multiple common types. Consider comparingshortandlongvalues. Because of type promotion, theshortwill be converted tolongfor comparison. However, some application constraint or invariant might let you know that both values can be represented by ashort. In this case, you may want to havecommon_type_min<short>(a,b).