简体   繁体   中英

c++11 use chrono as syntactic sugar

I use function from external library with interface like this: void f(int timeout); . Where timeout is in milliseconds. To make my code more readable, I want to use chrono in such form:

f(std::chrono::milliseconds(10).count());
  1. is it possible that std::chrono::milliseconds(10).count() != 10 ?

  2. is any "underwater rocks" that prevent modern compilers (clang, gcc, VC++) to convert f(std::chrono::milliseconds(10).count()) to f(10) ?

  1. is it possible that std::chrono::milliseconds(10).count() != 10 ?

No. The duration constructor you're using does:

3) Constructs a duration with r ticks.

and count() simply:

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

Nope. The duration constructor is constexpr , as is the count() member function you're using - that should be a very simple optimization for a compiler to make.


To make my code more readable [...]

Personally, I find that questionable. If f() itself took a duration , then f(std::chrono::milliseconds(10)) in of itself is certainly better than just f(10) , with the added benefit that whatever duration you pass in will work correctly. But if it's just taking an int , you're just giving yourself the illusion of security with just lots more typing. So I'm not sure it's any better, personally.

  1. No. But beware that the result is not milliseconds, but ticks. So std::chrono::seconds(10).count() is also 10. So you might want to do an assignment to a std::chrono::milliseconds variable first.

  2. No, because the method is a constexpr . So any good compiler should respect that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM