C++ 嘿,伙计们,试图用std::chrono从时间中减去持续时间,我搞砸了什么?
所以,我的代码没有编译,但我非常希望它能够编译。这是我的密码:C++ 嘿,伙计们,试图用std::chrono从时间中减去持续时间,我搞砸了什么?,c++,time,chrono,C++,Time,Chrono,所以,我的代码没有编译,但我非常希望它能够编译。这是我的密码: float numSeconds = 50; std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now(); auto duration = std::chrono::duration<float, std::chrono::seconds>(numSeconds); startTime -= duration; 我
float numSeconds = 50;
std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now();
auto duration = std::chrono::duration<float, std::chrono::seconds>(numSeconds);
startTime -= duration;
我得到以下错误代码:
Error C2679 binary '=': no operator found which takes a right-hand operand of type 'std::chrono::time_point<std::chrono::steady_clock,std::chrono::duration<float,std::ratio<1,1000000000>>>' (or there is no acceptable conversion)
错误C2679二进制“=”:未找到接受“std::chrono::time_point”类型的右操作数的运算符(或没有可接受的转换)
问题
std::chrono::stable\u clock::now()
的返回类型是std::chrono\u time\u point
std::chrono::duration
的第二个模板参数不符合指定的要求。例如,您会注意到编译错误静态断言失败:句点必须是与该行对应的ratio
的特化-=
运算符- 可以使用std::ratio表示秒
auto duration=std::chrono::duration(numSeconds);
//或者只需std::chrono::seconds(numSeconds)
- 尝试使用浮点类型表示时间可能不是一个好主意()。最好使用较小的单位(例如毫秒而不是秒),或者如果坚持使用浮点类型,则需要使用较大的类型,例如double(链接文档对此进行了解释)。像这样的事情似乎能让你的例子起作用
double numSeconds=50.0;
使用FpDurationT=std::chrono::duration;
使用TimepointT=std::chrono::time\u点;
TimepointT startTime=std::chrono::staid_clock::now();
自动持续时间=FpDurationT(numSeconds);
开始时间-=持续时间;
请添加错误消息的文本。std::chrono::staid_clock::now()
不是一个std::chrono::staid_clock
,它是一个std::chrono::time_point
,所以我猜第2行的赋值失败了。@NathanPierson第2行是我移植代码时的一个输入错误,没有失败,正如我所说,它在原位减法中失败了。我添加了支持此操作的错误消息。为什么不支持我的模板参数?我有一个秒数,需要将其指定为浮点,而不是int。另外,我认为std::chrono::seconds是有效的第二个参数?定义持续时间本身时,我没有收到任何警告。请在上面进行编辑,以回答您问题的前半部分。至于第二个,不,std::chrono::seconds
是std::chrono::duration
的别名-链接文档中明确提供了这些要求/定义。
"Error C2679 binary '-=': no operator found which takes a right-hand operand of type 'std::chrono::duration<float,std::chrono::seconds>' (or there is no acceptable conversion)"
timer.m_startTime = timer.m_startTime - duration;
Error C2679 binary '=': no operator found which takes a right-hand operand of type 'std::chrono::time_point<std::chrono::steady_clock,std::chrono::duration<float,std::ratio<1,1000000000>>>' (or there is no acceptable conversion)
auto duration = std::chrono::duration<std::int64_t, std::ratio<1,1>>(numSeconds);
// or simply std::chrono::seconds(numSeconds)