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?
Class template std::chrono::duration represents a time interval. It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational fraction representing the time in seconds from one tick to the next. The only data stored in a duration is a tick count of type Rep .
class Duration = typename Clock::duration. > class time_point; (since C++11) Class template std::chrono::time_point represents a point in time. It is implemented as if it stores a value of type Duration indicating the time interval from the start of the Clock 's epoch.
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.
You can use the following function:
#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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With