mercredi 29 août 2018

How to Implement a converter to proper duration type in below case

I have written a small TimeUnit code that aims to implement duration types using easy to understand Enums and it works fine in implementing delay function. I want to write a converter which returns the required duration given The quantity and TimeUnit type. Can someone shed how I can implement this? I tried methods of template specialization but it is not working.

I need function say toDuration(const long&, const TimeUnit&) and returns appropriate type of duration which is say suitable for passing to condition_variable wait_for or any sleep_for delay function.

Ex:- toDuration(10, TimeUnit::MilliSeconds) should return std::chrono::milliseconds(10) and so on [ scope only for below types of Enums is fine ].

class TimeUnit_impl
{
    public:
        typedef std::chrono::duration<long, std::ratio<1l, 1000l> > MILLISECONDS;
        typedef std::chrono::duration<long, std::ratio<1l, 1000000l> > MICROSECONDS;
        typedef std::chrono::duration<long, std::ratio<1l, 1l> > SECONDS;
        typedef std::chrono::duration<long, std::ratio<1l, 1000000000l> > NANOSECONDS;
        typedef std::chrono::duration<long, std::ratio<60> > MINUTES;
        typedef std::chrono::duration<long, std::ratio<3600> > HOURS;
};

enum class TimeUnit { MilliSeconds , MicroSeconds , Seconds, NanoSeconds, Minutes, Hours };

void customSleep(const long& quantity, const TimeUnit& unit)
{
    switch(unit)
    {
        case TimeUnit::MilliSeconds : std::this_thread::sleep_for(TimeUnit_impl::MILLISECONDS(quantity));
                                      break;
        case TimeUnit::MicroSeconds : std::this_thread::sleep_for(TimeUnit_impl::MICROSECONDS(quantity));
                                      break;
        case TimeUnit::Seconds :      std::this_thread::sleep_for(TimeUnit_impl::SECONDS(quantity));
                                      break;
        case TimeUnit::NanoSeconds :  std::this_thread::sleep_for(TimeUnit_impl::NANOSECONDS(quantity));
                                      break;
        case TimeUnit::Minutes :      std::this_thread::sleep_for(TimeUnit_impl::MINUTES(quantity));
                                      break;
        case TimeUnit::Hours :        std::this_thread::sleep_for(TimeUnit_impl::HOURS(quantity));
                                      break;
        default:            std::cout << "error" << std::endl;
                            break;
    }
}

Aucun commentaire:

Enregistrer un commentaire