c – 隐式转换以适应现有构造函数

c – 隐式转换以适应现有构造函数,第1张

概述我的主要目标是拥有类似的东西: 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 我的主要目标是拥有类似的东西:

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}};

编辑:
这个问题不仅指向编译问题,因为它只是一个错字,你为我解决了.谢谢,抱歉这个蠢事.

但:
有没有办法摆脱代码行中的Tm?问题是:

如果不从时钟类型派生,则无法“引入”其他构造函数.
转换运算符无法帮助“动态”编译器无法看到该类型.所以

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"intmain(){    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中.

总结

以上是内存溢出为你收集整理的c – 隐式转换以适应现有构造函数全部内容,希望文章能够帮你解决c – 隐式转换以适应现有构造函数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1229192.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存