gpt4 book ai didi

c++ - std::chrono::duration 可以按秒初始化,但不能按毫秒初始化?

转载 作者:行者123 更新时间:2023-12-02 00:32:56 28 4
gpt4 key购买 nike

作品: std::chrono::duration<unsigned long long> test1 = std::chrono::seconds(1);

不起作用: std::chrono::duration<unsigned long long> test2 = std::chrono::milliseconds(1);

为什么有区别?持续时间内部是否没有足够的粒度?

从以毫秒为单位的值初始化持续时间的首选方法是什么?

最佳答案

std::chrono::duration 的模板参数列表采用两个参数:保存基础数据的类型和 std::ratio代表持续时间指数的参数。类似 std::chrono::seconds 的类型和std::chrono::milliseconds是该模板的特化,使用 std::chrono::duration<int64_t, std::ratio<1>>std::chrono::duration<int64_t, std::ratio<1, 1000>>分别。

如果您不提供std::ratio类型参数,默认为 std::ratio<1> .

因此,您的自定义持续时间类型隐式采用 std::chrono::duration<unsigned long long, std::ratio<1>> 形式,这使得它几乎等于 std::chrono::seconds (唯一的区别是无符号值而不是有符号值),但因为它的比率高于提供给 std::chrono::milliseconds 的比率,类模板禁止赋值/原始转换。在这种情况下,如果您希望分配成功,则需要显式转换它:

typedef std::duration<unsigned long long> my_duration;
//my_duration test1 = std::chrono::milliseconds(1);//Forbidden
my_duration test1 = std::chrono::duration_cast<my_duration>(std::chrono::milliseconds(1)); //Permitted, will be truncated
my_duration test2 = std::chrono::duration_cast<my_duration>(1ms); //Permitted, may be easier to read

std::ratio参数表示持续时间的刻度大小。刻度尺寸越小,代表持续时间的基础数字就越大。举个例子:

using seconds = std::chrono::seconds; //std::duration<int64_t, std::ratio<1,1>>
using milliseconds = std::chrono::milliseconds; //std::duration<int64_t, std::ratio<1,1000>>
using nanoseconds = std::chrono::nanoseconds; //std::duration<int64_t, std::ratio<1,1000000000>>

seconds time1 = 5s; //underlying integer value is 5.
milliseconds time2 = 5ms; //underlying integer value is 5.
time2 = time1; //underlying integer value for time2 is 5000, for time1 is still 5.
time2 = 17ms; //underlying integer value is 17.
//time1 = time2; //forbidden; tick size of time2 is smaller than time1
time1 = std::chrono::duration_cast<seconds>(time2);
//underlying integer value for time1 is 0, due to truncation; time2 is still 17.
nanoseconds time3 = 5ms; //underlying integer value is 5000000.
time1 = 2s; //underlying integer value is 2.
time3 = time1; //underlying integer value is 2000000000.

关于c++ - std::chrono::duration 可以按秒初始化,但不能按毫秒初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52506741/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com