std::min 种不同类型 std::chrono::duration 种

std::min of std::chrono::duration of different types

考虑以下代码:

// 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> 明确指定类型。在此代码的未来版本中,类型会有所不同。在不知道确切持续时间类型的情况下执行此操作的通用方法是什么?

给定两个持续时间,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]。

您可以使用以下功能:

#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);
}