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

Consider the following code:

// 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);

It does not compile because the compiler cannot create the correct version std::mindue to different types of arguments.

Of course, you can now explicitly specify the type using std::min<milliseconds>. In future versions of this code, the types will be different. What is the general way to do this without knowing the exact duration types?

+4
source share
2 answers

Given two durations, D1 d1and D2 d2...

You can convert both durations to their common type std::common_type_t<D1, D2>, and then find the minimum of these values.

std::min<std::common_type_t<D1, D2>>(d1, d2) .

, std::common_type duration, . [time.traits.specializations] ++.

+8

:

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

Source: https://habr.com/ru/post/1661866/


All Articles