我使用来自外部库的函数,接口(interface)如下:void f(int timeout);
。
其中 timeout
以毫秒为单位。为了使我的代码更具可读性,我想以这种形式使用 chrono
:
f(std::chrono::milliseconds(10).count());
std::chrono::milliseconds(10).count() != 10
有可能吗?是任何阻止现代编译器(clang、gcc、VC++)将
f(std::chrono::milliseconds(10).count())
转换为的“水下岩石”f(10)
?
最佳答案
- is it possible that
std::chrono::milliseconds(10).count() != 10
?
没有。 duration
constructor你正在使用:
3) Constructs a duration with
r
ticks.
和count()
简单地:
Returns the number of ticks for this duration.
- is any "underwater rocks" that prevent modern compilers (clang, gcc, VC++) to convert
f(std::chrono::milliseconds(10).count())
tof(10)
?
没有。 duration
构造函数是 constexpr
,您正在使用的 count()
成员函数也是如此 - 这对编译器来说应该是一个非常简单的优化制作。
To make my code more readable [...]
就我个人而言,我觉得这有问题。如果 f()
本身 花费 duration
,则 f(std::chrono::milliseconds(10))
本身肯定比 f(10)
更好,还有一个额外的好处,即无论您传入的持续时间如何,都可以正常工作。但是,如果它只是采用 int
,那么您只会给自己一种安全的错觉,而只需输入更多的代码。所以我个人不确定它是否更好。
关于c++11 使用 chrono 作为语法糖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36843018/