跳转至内容
  • 关于c++ chrono库中类型方面的问题

    未解决 General Discussion | 综合讨论
    2
    0 赞同
    2 帖子
    21 浏览
    sunrisepeakS

    chrono:xxseconds 一般是duration的别名

    _EXPORT_STD using nanoseconds = duration<long long, nano>; _EXPORT_STD using microseconds = duration<long long, micro>; _EXPORT_STD using milliseconds = duration<long long, milli>; _EXPORT_STD using seconds = duration<long long>; _EXPORT_STD using minutes = duration<int, ratio<60>>; _EXPORT_STD using hours = duration<int, ratio<3600>>;

    而duration的构造存在隐式类型转换, 他的构造函数是一个模板, 在构造函数里会使用duration_cast把std::chrono::milliseconds转成chrono::microseconds

    template <class _Rep2, enable_if_t<is_convertible_v<const _Rep2&, _Rep> && (treat_as_floating_point_v<_Rep> || !treat_as_floating_point_v<_Rep2>), int> = 0> constexpr explicit duration(const _Rep2& _Val) noexcept(is_arithmetic_v<_Rep> && is_arithmetic_v<_Rep2>) // strengthened : _MyRep(static_cast<_Rep>(_Val)) {} template <class _Rep2, class _Period2, enable_if_t<treat_as_floating_point_v<_Rep> || (_Ratio_divide_sfinae<_Period2, _Period>::den == 1 && !treat_as_floating_point_v<_Rep2>), int> = 0> constexpr duration(const duration<_Rep2, _Period2>& _Dur) noexcept(is_arithmetic_v<_Rep> && is_arithmetic_v<_Rep2>) // strengthened : _MyRep(_CHRONO duration_cast<duration>(_Dur).count()) {} // 具体转换的代码 _NODISCARD constexpr _Rep count() const noexcept(is_arithmetic_v<_Rep>) /* strengthened */ { return _MyRep; }

    https://github.com/microsoft/STL/blob/a1bc1261795d4097cf7c12cfd0b5e2091809f281/stl/inc/__msvc_chrono.hpp#L110-L117