7

我是否正确地阅读了从minmaxminmax就此而言)有新的initializer_list变体但没有Variadic Template变体的标准?

因此,这没关系:

int a = min( { 1,2,a,b,5 } );

但这不是:

int b = min( 1,2,a,b,5 ); // err!

我想,很多人会期望 Variadic Templates 可以轻松实现这一点,因此他们可能会感到失望。

我会说将VT用于min并且max会矫枉过正

  • 可变参数模板能够处理多种类型
  • 初始化器列表检查所有类型在设计上是否相同

因此 IL 更适合这项任务。

我的解释正确吗?

4

4 回答 4

10

你的解释是正确的。 N2772包含更深入的原理。

于 2011-05-29T13:48:40.447 回答
1

这是我在 GCC 4.6 上使用带有和不带有Boost Concepts Common Type Traits的可变参数模板的解决方案。min不过,我不确定是否需要 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)...);
}
于 2011-09-19T13:58:07.693 回答
0

是的,我认为公平地说,让所有值都是兼容类型使得列表成为此功能的良好候选者。这并不是说您不能编写自己的可变参数模板版本。

于 2011-05-29T13:45:02.290 回答
0

通过结合可变参数模板和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...});
}
于 2018-09-10T05:52:47.670 回答