【发布时间】:2011-11-24 06:54:39
【问题描述】:
我需要反思我对std::min、std::max 的 C++11 可变参数版本的实现。这是我对std::min 的两个替代方案,其中std::max 的实现方式类似,只需将std::min 替换为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...)));
}
关键问题是我们是否需要common_type_min?请注意,这允许使用一个参数调用 min()。这会导致混乱或问题吗?
【问题讨论】:
-
在获得 2 个参数之前不能递归吗?没有要求专门停止在 1 个参数。
-
我知道该怎么做。我只是想知道是否最好允许
min和max采用一个参数,以便在容器包装器(例如std::tuple)上实现算法通用性。 -
我倾向于说单个值的最小值没有意义,但 1 元素元组的最小值确实有意义。也许对容器类型重载
min()会更好。
标签: c++ max minimum variadic-templates