接受任何表示/时间段的std :: chrono :: duration [英] Accepting std::chrono::duration of any representation/period

查看:134
本文介绍了接受任何表示/时间段的std :: chrono :: duration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望函数以对调用者有意义的单位接受持续时间。

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

例如:

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?

推荐答案

有一些常用选项

1)使用模板。这样做的好处是没有转换,但是需要使用模板,而这可能是不可能的。例如,如果这是虚拟功能的接口。

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)使用整数表示法,以及界面需要的最低Period。例如,如果您的函数实际上只需要纳秒,那么您可以直接使用它。如果不发生精度损失,则将隐式转换为纳秒。您可以使用预定义的时间段指定其他时间段,也可以将其明确指定为持续时间的一部分

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)使用双精度表示法,如果精度不是问题,这可能很有用,但是接受所有输入的能力是。这将隐式转换任何持续时间,因为在所有期间都允许转换为浮点类型。例如,如果您想要双精度秒,则可以这样做

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

这篇关于接受任何表示/时间段的std :: chrono :: duration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆