Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Casting double chrono::seconds into millisecond

im have simple function like

void foo(std::chrono::milliseconds ms) {
    std::cout << ms.count() << " milliseconds" << std::endl;
}

and next im calling them by

int main() {
    using namespace std::chrono_literals;

    boo(3s);
    boo(1h);
    boo(100ms);
}

Output is simple:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

3000 milliseconds
3600000 milliseconds
100 milliseconds

But, what if im wanna to use this function with:

    boo(3.5s);
    boo(0.5s);
    boo(0.3days);

Then i have compile error.
So, i can write function who receive chrono::duration:

template<class T>
void foo(std::chrono::duration<T> duration) {
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " milliseconds" << std::endl;
}

and then 3.5s will work, but 1h or 3.5h isnt work.
So, question, can im write universal function which convert any of 1s/1.s/1m/1.5m/1h/1.5h/etc into milliseconds ?
Maybe i can create overloaded operators for chrono::seconds / hours ?
Or just cast, cast, cast ?

Im trying all described below/above

>Solution :

The proper function template definition should take the period as a template parameter too:

template <class Rep, class Period>
void boo(std::chrono::duration<Rep, Period> duration) {
    
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(duration)
                     .count()
              << " milliseconds\n";
}

Or in C++20, don’t call .count() and let it print the unit automatically:

template <class Rep, class Period>
void boo(std::chrono::duration<Rep, Period> duration) {
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(duration)
              << '\n';
}

I have no clue about the days literal though. Never seen it, but the rest of them will work.

int main() {
    using namespace std::chrono_literals;

    boo(3s);
    boo(1h);
    boo(100ms);

    boo(3.5s);
    boo(0.5s);
    boo(std::chrono::days(1) * 0.3); // what I got working
}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading