c++11 使用 chrono 作为语法糖

标签 c++ c++11

我使用来自外部库的函数,接口(interface)如下:void f(int timeout);。 其中 timeout 以毫秒为单位。为了使我的代码更具可读性,我想以这种形式使用 chrono:

f(std::chrono::milliseconds(10).count());
  1. std::chrono::milliseconds(10).count() != 10 有可能吗?

  2. 是任何阻止现代编译器(clang、gcc、VC++)将 f(std::chrono::milliseconds(10).count()) 转换为的“水下岩石” f(10)?

最佳答案

  1. 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.


  1. is any "underwater rocks" that prevent modern compilers (clang, gcc, VC++) to convert f(std::chrono::milliseconds(10).count()) to f(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/

相关文章:

c++ - 接收仿函数作为参数的最通用方法?

c++ - 将 std::atomic_flag 包装在 getter/setter 中是否会使它的 "atomicity"无效?

c++ - 我们应该如何实现对象类型的 move ?

为 HTTPS 查询发回简单字符串的 C++ 库

c++ - libGL 堆使用

c++ - 使用基于范围的 for 循环为 vector 赋值

c++ - 使用公钥 : BER decode error 加密消息

C++变量和调试器之间的不同值

c++ - Linux 和 macOS 没问题,但 Windows 构建会抛出链接器错误 LNK2019

c++ - C++中long double的精度是多少?