Consider 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 doesn't compile because compiler cannot instantiate correct version of std::min
because of different argument types.
Of course, now it's possible to specify type explicitly using std::min<milliseconds>
. In future versions of this code, types will vary. What is the generic way of doing that without knowing exact duration types?
Given two durations, D1 d1
and D2 d2
...
You can convert both durations to their common type, std::common_type_t<D1, D2>
, and then find the minimum of those values.
Or just call std::min<std::common_type_t<D1, D2>>(d1, d2)
and let them be converted to that type as needed.
This works because std::common_type
is specialized to do the right thing for duration
types, see [time.traits.specializations] in the C++ standard.