c – 隐式转换以适应现有构造函数
我的主要目标是拥有类似的东西:
std::chrono::high_resolution_clock tp4{ 2013,1,2,10,11,12,-1,1234 }; 所以我创建了一个涵盖tm对象的类,如下所示: struct Tm : std::tm { int tm_usecs; // [0,999999] micros after the sec Tm(const int year,const int month,const int mday,const int hour,const int min,const int sec,const int usecs,const int isDST = -1) : tm_usecs{usecs} { tm_year = year - 1900; // [0,60] since 1900 tm_mon = month - 1; // [0,11] since Jan tm_mday = mday; // [1,31] tm_hour = hour; // [0,23] since midnight tm_min = min; // [0,59] after the hour tm_sec = sec; // [0,60] after the min // allows for 1 positive leap second tm_isdst = isDST; // [-1...] -1 for unknown,0 for not DST,// any positive value if DST. } template <typename Clock_t = std::chrono::high_resolution_clock,typename MicroSecond_t = std::chrono::microseconds> auto to_time_point() const -> typename Clock_t::time_point { auto tmp = *this; // hack to get it a const auto time_c = mktime(&tmp); return Clock_t::from_time_t(time_c) + MicroSecond_t{tm_usecs}; } operator std::chrono::high_resolution_clock::time_point () const { return to_time_point(); } }; 好的,现在我可以写: Tm ttt{2013,1234}; std::chrono::high_resolution_clock::time_point tp3{ttt}; 要么 std::chrono::high_resolution_clock::time_point tp4{Tm{2013,1234}}; 编辑: 但: 如果不从时钟类型派生,则无法“引入”其他构造函数. std::chrono::high_resolution_clock::time_point tp4{{2013,1234}}; 无法工作. 所以问题就是可能有一个hack来获取初始化列表在这里从time_point接受.也许可以用用户定义的演绎指南写一些东西. 从Howards回答我看到了使用用户定义的文字引入类型然后可以转换的想法.感谢那! 解决方法
high_resolution_clock与人类日历没有可移植的关系.例如,在我的平台(macOS)上,它测量自计算机启动以来的时间.
但你可以瞄准system_clock.虽然目前没有指定时代,但事实上的标准是它测量自1970-01-01 00:00:00 UTC(不包括闰秒)以来的时间.该纪元目前在upcoming C++20 draft中指定. Here is a free,open-source library,which I have written,用你稍微不同的语法做你想要做的事情: #include "date/date.h" int main() { using namespace date; using namespace std::chrono; system_clock::time_point tp = sys_days{2013_y/January/2} + 10h + 11min + 12s + 1234us; } 日期/时间以UTC指定.如果您需要指定相对于时区的日期/时间,则可以使用additional library来实现. 这两个库也都在C++20 working draft中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |