为什么C++引入duration_cast而不是使用static_cast?

jww*_*jww 7 c++ casting duration

我正在查看一些使用过的代码duration_cast.看着它我想知道为什么static_cast没有使用,因为static_cast生活中的目的是在类型之间进行转换.

为什么C++需要一个新的运算符来在时间之间进行转换?为什么没用static_cast


也许我不理解C++在毫秒,微秒,纳秒等之间的差异.出于某种原因,我认为答案很明显或在Stack Overflow上讨论过,但我还没有找到它(然而).

Ric*_*ges 5

当没有精度损失风险时,已经有时间间隔的直接转换.duration_cast当存在精度损失的风险时需要.

duration_cast 因此,不是故意转换的操作者.

static_cast因为不同的持续时间类型不相关,所以不适合.它们完全是不同的类,恰好支持相同的概念.

例如:

#include <chrono>

int main()
{
  using namespace std::literals;

  // milliseconds    
  auto a = 10ms;

  // this requires a duration-cast
  auto lossy = std::chrono::duration_cast<std::chrono::seconds>(a);

  // but this does not
  auto not_lossy = std::chrono::nanoseconds(a);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@理查德。我的部分(大部分?)困惑是因为它的命名方式而相信它是一个内置的运算符。事实上,我在问题中称其为运算符,dasblinkenlight 就注意到了它。如果您添加一些关于它不是运营商的内容,那么我应该能够接受。 (2认同)

How*_*ant 5

多年来,我多次重温这个问题,现在我认为这可能是我的设计错误。

我目前正在尝试更多地依赖显式转换语法来进行不应隐式进行的转换,而不是“命名转换语法”。

例如:

https://howardhinnant.github.io/date/date.html#year

year y = 2017_y;
int iy = int{y};  // instead of iy = y.to_int()
Run Code Online (Sandbox Code Playgroud)