开发者

Reflections on C++ Variadic Templated Versions of std::min() and std::max()

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:

/*! Multi-Type Minimum of \p a and \p args. */
template <class T, class U >
//requires SameType <T , U >...
T multi_type_min(const T & a, const U & b)
{
    return std::min(a, b);
}

/*! Multi-Type Minimum of \p a and \p args. */
template <class T, class U, class ... R >
//requires SameType <T , U, Args >...
T multi_type_min(const T & a, const U & b, const R &... c)
{
    return std::min(a, multi_type_min(b, c...));
}

I'm guessing the common_type_min variant is necessary when there are multiple common types. Consider comparing short and long values. Because of type promotion, the short will be converted to long for comparison. However, some application constraint or invariant might let you know that both values can be represented by a short. In this case, you may want to have common_type_min<short>(a,b).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜