c++ - 编译c++11的chrono time时报错

标签 c++ c++-chrono

最喜欢的代码

  uint64_t nanoseconds = 0;
  auto nano = std::chrono::nanoseconds(nanoseconds_);
  system_clock::time_point tp(nano);

报错(QNX):

time.cpp:86:35: error: no matching function for call to 'std::__1::chrono::time_point<std::__1::chrono::system_clock>::time_point(std::__1::chrono::duration<long long int, std::__1::ratio<1l, 1000000000l> >&) 
qnx700/target/qnx7/usr/include/c++/v1/chrono:769:5: note: candidate: 
template<class _Duration2> std::__1::chrono::time_point<_Clock, _Duration>::time_point(const std::__1::chrono::time_point<_Clock, _Duration2>&,
typename std::__1::enable_if<std::__1::is_convertible<_Duration2, 
_Duration>::value>::type*) time_point(const time_point<clock, _Duration2>& t,
^ qnx700/target/qnx7/usr/include/c++/v1/chrono:769:5: note: template argument 
deduction/substitution failed: time.cpp:86:35: note: 
'std::__1::chrono::duration<long long int, std::__1::ratio<1l, 1000000000l> >'
 is not derived from 'const 
 std::__1::chrono::time_point<std::__1::chrono::system_clock, _Duration2>''

如何将 std::chrono::nanosecondstime_point 结合使用

谢谢大家。

最佳答案

std::chrono::time_point does not have a constructor任意持续时间类型作为模板参数。接受system_clock::time_point::duration的构造函数构造一个时间点,其time_since_epoch()属性设置为指定的参数,即构造的时间点表示在其“epoch”之后的指定持续时间的时间。

如果这是您的意图,您可以使用 duration_cast 将您的纳秒值转换为 system_clock::time_point::duration :

using namespace std::chrono;

nanoseconds nano(1234567);

system_clock::time_point time(
    duration_cast<system_clock::duration>(nano));

或者,您可以构建一个持续时间为零的 system_clock::time_point(即代表纪元的时间点),然后将您的纳秒值添加到此;结果是一个新的时间点:

system_clock::time_point epoch;
system_clock::time_point time = epoch + nano;

正如 Howard Hinnant 所暗示的那样,该标准不保证 std::chrono::system_clock::duration 的任何特定精度,即系统时钟可能无法测量小至纳秒的间隔。在我的系统(Linux x86_64、gcc 7.3/glibc 2.20)上,持续时间精度为 1 纳秒,但在其他平台上可能为 1 微秒或更短。在这样的平台上,duration_cast<system_clock::duration>(nanoseconds(1)) 的结果为零,因为 duration_cast rounds toward zero

(另请注意,即使精度为 1 纳秒,准确度 也可能不是!不过这是另一个话题。)

关于c++ - 编译c++11的chrono time时报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53376010/

相关文章:

c++ - 强制列表初始化矩阵的大小

c++ - 如何位移 u16* 的数据?

c++ - Qt Creator 在 Mac 上启动调试失败

c++11 - 如何序列化 std::chrono::分钟

c++ - 如何检查 duration_cast 是否溢出

c++ - 如何比较 time_t 和 std::filesystem::file_time_type

c++ - lldb: vector 元素的自定义摘要(C++)

c++ - 来自子类的虚函数调用一次父函数

c++ - Java 到 C++ UTC 时间 - 以秒为单位查找 Utc 时区时间偏移

c++ - std::chrono::high_resolution_clock - 时间测量