C ++ 11中的min和max Variadic模板变体?

问题描述 投票:7回答:4

我是否正确阅读minmax(以及minmax)的标准,有新的initializer_list变体,但没有Variadic模板变体?

这样就可以了:

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

但这不是:

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

我想,很多人都希望Variadic模板可以很容易地实现这一点,因此他们可能会感到失望。

我会说使用V.T.因为minmax会有点矫枉过正

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

因此I.L.更适合这项任务。

我的解释是否正确?

c++ c++11 variadic-templates initializer-list stl-algorithm
4个回答
10
投票

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


1
投票

这是我的解决方案,使用带有和不带Boost Concepts的变量模板,在GCC 4.6上测试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)...);
}

0
投票

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


0
投票

通过组合variadic模板和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...});
}
© www.soinside.com 2019 - 2024. All rights reserved.