Brian McFarland Brian McFarland - 1 month ago 7
C++ Question

Class that stores a std::chrono::duration as a member?

I want to create a class who's construct takes a

std::chrono::duration
argument and stores the result in a member so that I can later pass it into
std::this_thread::sleep_for()
.

I know I can write some function template that works like
sleep_for
as follows:

template <typename Rep, typename Period>
void mySleep( std::chrono::duration<Rep, Period> time )
{
std::this_thread::sleep_for(time);
}


And this could be a member function of a class. But what about the following case?

class UsesDuration
{
public:
template <typename Rep, typename Period>
UsesDuration( std::chrono::duration<Rep, Period> dur ) :
my_duration(dur) { }

void doSomethingPeriodic()
{
while( some_condition )
{
std::this_thread::sleep_for(my_duration);
somethingInteresting();
}
}

private:
??? my_duration; /* How do I declare this??? */
}


Is there a clean way to keep the duration "abstract" A) ideally w/o turning the entire class into a templated class, B) by turning the class into a class template?

Answer

One solution I can see for this is to just use a particular duration in you class and then you can use std::chrono::duration_cast to cast from the type supplied to the constructor to the type you use as the class member. This allows you to not template the class but still take in any type of duration

template <typename Rep, typename Period>
   UsesDuration( std::chrono::duration<Rep, Period> dur ) :
      my_duration(std::chrono::duration_cast<decltype(my_duration)>(dur)) { }
Comments