【问题标题】:Reflections on C++ Variadic Templated Versions of std::min() and std::max()关于 std::min() 和 std::max() 的 C++ 可变参数模板版本的思考
【发布时间】:2011-11-24 06:54:39
【问题描述】:

我需要反思我对std::minstd::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 个参数。
  • 我知道该怎么做。我只是想知道是否最好允许 minmax 采用一个参数,以便在容器包装器(例如 std::tuple)上实现算法通用性
  • 我倾向于说单个值的最小值没有意义,但 1 元素元组的最小值确实有意义。也许对容器类型重载min() 会更好。

标签: c++ max minimum variadic-templates


【解决方案1】:

你不能把它写成递归直到你在两个参数处停止吗?

这是一个(未经测试的)sn-p:

/*! 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...));
}

我猜当有多种常见类型时,common_type_min 变体是必要的。考虑比较 shortlong 值。由于类型提升,short 将转换为long 以进行比较。但是,某些应用程序约束或不变量可能会让您知道这两个值都可以用short 表示。在这种情况下,您可能需要common_type_min&lt;short&gt;(a,b)

【讨论】:

  • 请注意,此版本的multi_type_min正确关联的。我们不应该更喜欢左吗?
  • @Nordlöw:在我看来是一个武断的决定。为什么要在左操作数的类型中执行所有比较? std::min(1, 1.0) 不应该返回双精度数吗?如果是这样,multi_type_min(1, 1, 1, 1, 1.0) 不应该也返回一个双精度值吗?
猜你喜欢
  • 2016-06-11
  • 2011-08-02
  • 2022-01-05
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 2019-03-03
  • 1970-01-01
相关资源
最近更新 更多