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

前端 未结 1 1818
太阳男子
太阳男子 2021-01-04 02:47

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

For example:

transition->after(chrono::seconds(3));
transition         


        
相关标签:
1条回答
  • 2021-01-04 03:22

    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);
    
    0 讨论(0)
提交回复
热议问题