dimanche 24 mai 2015

std::tm to chrono time point, something is strange

Check this code, I'd like to convert a std::tm to a chrono time point and to do so I use the standard function std::mktime.

There is some machinery to unset the TZ environmental variable in order to ignore the local time zone, but the code should be fairly straight forward.

template <class TimePoint>
TimePoint broken2time_point(std::tm& tm) {
    // "TZ" env variable must be empty to mktime to work without considering the timezone
    struct ResetTZ {
        ResetTZ()
         :  tzenv_ { getenv("TZ") },
            tzenvc_ {} {
                if (tzenv_) tzenvc_ = tzenv_;
                setenv("TZ", "", 1);
                tzset(); }
       ~ResetTZ() {
            if (tzenv_) setenv("TZ", tzenvc_.c_str(), 1);
            else unsetenv("TZ");
            tzset(); }

        char* tzenv_;
        std::string tzenvc_;
    } reset_tz;

    auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));
    auto mtp = std::chrono::time_point_cast<typename TimePoint::duration, typename TimePoint::clock>(tp);

    return mtp;
}

Besides the code also seems to work fine, however I have a question.

Read the line about the std::chrono::time_point_cast; according to the cppreference time point cast page the template parameters should be Clock and Duration not viceversa.

Where is the mistake? I am missing something? cpprefence is wrong?

Aucun commentaire:

Enregistrer un commentaire