【问题标题】:std::min of std::chrono::duration of different types不同类型的 std::chrono::duration 的 std::min
【发布时间】:2016-11-24 15:22:42
【问题描述】:

考虑以下代码:

// durations are from std::chrono
auto a = get_duration_1(); // milliseconds, will vary in future versions
auto b = get_duration_2(); // seconds, will vary in future versions
auto c = std::min(a, b);

由于参数类型不同,编译器无法实例化正确版本的std::min,因此无法编译。

当然,现在可以使用std::min<milliseconds> 显式指定类型。在此代码的未来版本中,类型会有所不同。在不知道确切的持续时间类型的情况下,通用的方法是什么?

【问题讨论】:

  • 如果没有为std::min 指定和现有的std::chrono::duration 专业化(并且没有),那么就没有通用(和“好”)的方式。除了自己做这样的专业。如果您在多个地方需要它,那么这样的专业化可能是个好主意。
  • std::min 没有任何版本可以接受不同的参数类型。要么转换其中一个论点,要么同时转换两者。
  • 我更改了问题,以便明确显示对通用代码的需求。
  • 请注意,转换为较低分辨率的 TimePoint 会截断,因此需要显式转换才能实现您想要的目标。
  • @doug 感谢您的有用评论。问题是我想避免这种情况。 (例如,将microseconds(可能在将来出现)转换为milliseconds。)这就是我寻找通用方式的原因。

标签: c++ c++11 chrono stl-algorithm


【解决方案1】:

给定两个持续时间,D1 d1D2 d2 ...

您可以将两个持续时间转换为它们的通用类型std::common_type_t<D1, D2>,然后找到这些值中的最小值。

或者只是调用std::min<std::common_type_t<D1, D2>>(d1, d2) 并让它们根据需要转换为该类型。

这是因为 std::common_type 专门为 duration 类型做正确的事情,请参阅 C++ 标准中的 [time.traits.specializations]。

【讨论】:

  • 那可以封装在函数模板中,不是吗?有用的实用程序,不仅仅是std::chrono
  • 看起来像一个解决方案。在这种带有auto 变量的特定情况下,我应该使用std::common_type<decltype(a), decltype(b)>吗?
  • 是的,当然。在你的情况下,D1decltype(a)D2decltype(b),所以相应地替换。但要小心:那应该是common_type_t 而不是common_type
  • 我打错了,忘记了_t。正确版本:std::common_type_t<decltype(a), decltype(b)>.
【解决方案2】:

您可以使用以下功能:

#include <chrono>

template <typename T1, typename T2>
auto generic_min(const T1& duration1, const T2& duration2)
{
    using CommonType = typename std::common_type<T1,T2>::type;
    const auto d1 = std::chrono::duration_cast<CommonType>(duration1);
    const auto d2 = std::chrono::duration_cast<CommonType>(duration2);
    return std::min(d1,d2);
}

【讨论】:

  • 很遗憾,我只能将一个答案标记为正确。感谢您提供准确的代码!
猜你喜欢
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2012-08-21
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多