Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting std::chrono::duration of any representation/period

Tags:

c++

c++11

I want a function to accept a duration in whatever units makes sense to the caller.

For example:

transition->after(chrono::seconds(3));
transition->after(chrono::milliseconds(500));
transition->after(chrono::hours(1));

What would a valid signature for this after function look like? Can I avoid making it a templated function?

like image 982
Drew Noakes Avatar asked Mar 12 '14 20:03

Drew Noakes


1 Answers

There are a handful of common options

1) Use a template. This has the advantage that there is no conversion, but requires the use of a template, which might not be possible. For example, if this is an interface for a virtual function.

template<typename Rep, typename Period>
void after( std::chrono::duration< Rep, Period > t);

2) Use an integer representation, and the lowest Period your interface needs. For example, if your function realistically only needs nanoseconds, then you could use that directly. This will implicitly convert to nanoseconds, if no loss of precision would occur. You can specify other periods using the pre-defined ones, or explicitly specifying it as part of the duration

void after( std::chrono::nanoseconds t) ;

3) Use a double representation, which can be useful if the precision isn't an issue, but the ability to accept all inputs is. This will implicitly convert any duration, since conversion to a floating point type is allowed for all periods. For example, if you wanted double-precision seconds, you would do

void after( std::chrono::duration< double > t);
like image 69
Dave S Avatar answered Oct 05 '22 22:10

Dave S