C ++ 11中最小和最大可变参数模板变体?

| 我在阅读从
min
max
(以及
minmax
)开始有新的initializer_list变体,但没有可变参数模板变体的标准对吗? 因此,这没关系:
int a = min( { 1,2,a,b,5 } );
但这不是:
int b = min( 1,2,a,b,5 ); // err!
我猜想,很多人会希望可变参数模板可以轻松实现这一目标,因此可能会感到失望。 我会说使用V.T.
min
max
会被杀 可变参数模板能够处理多种类型 初始化程序列表检查设计是否所有类型都相同 因此更适合该任务。 我的解释正确吗?     
已邀请:
        您的解释是正确的。 N2772包含更深入的原理。     
        这是我在GCC 4.6上使用带有和不带有Boost Concepts Common Type Traits forѭ0的可变参数模板的解决方案。不过,我不确定是否需要common_type。
#define LessThanComparable class
#include <boost/type_traits/common_type.hpp>


/*! 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, \\p b and \\p args. */
template <class T, class ... R >
//requires SameType <T , Args >...
T multi_type_min(const T & a, const T & b, const R &... args)
{
    return multi_type_min(a < b ? a : b, args...);
}

/*! Minimum of \\p a. */
template <LessThanComparable T> const T & min(const T & a) { return a; } // template termination
/*! Minimum of \\p a, \\p b and \\p args. */
template <class T, class U, class ... R, class C = typename boost::common_type<T, U, R...>::type >
C min(const T & a, const U & b, const R &... c)
{
    return min(static_cast<C>(a < b ? a : b), static_cast<C>(c)...);
}
    
        是的,我认为可以说所有值都是兼容类型使得列表很适合此功能。这并不是说您无法编写自己的可变参数模板版本。     
        通过组合可变参数模板和initializer_list,我们可以使函数
int b = min( 1,2,a,b,5 );
工作而无需递归展开。
template <class T>
T _real_min_(T a, std::initializer_list<T> s) {
    T *res = &a;
    for (auto it = s.begin(); it != s.end(); ++it) {
        *res = *(it) < *res ? *it : *res;
    }
    return *res;
}

template <class T, class... ArgTypes>
T min(T a, ArgTypes... args) {
  return _real_min_(a, {args...});
}
    

要回复问题请先登录注册