The class in which std :: chrono :: duration is stored as a member?

I want to create a class that builds, takes an argument, std::chrono::durationand stores the result in a member, so I can pass it to std::this_thread::sleep_for().

I know that I can write a function template that works like sleep_forthis:

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

And it 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 preserve the duration of “abstract” A) ideally without turning the entire class into a template class, B) turning the class into a class template?

+4
source share
2 answers

, , - , std::chrono::duration_cast , , , . ,

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

std::chrono::duration, , - :

#include <chrono>
#include <thread>

class UsesDuration
{
public:
   UsesDuration( std::chrono::nanoseconds dur ) :
      my_duration(dur) { }

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

   void somethingInteresting();

private:
   std::chrono::nanoseconds  my_duration;
};

int
main()
{
    using namespace std::chrono_literals;
    UsesDuration x{5min};
}

, . nanoseconds. - , , nanoseconds, , , , , .

, , double, :

#include <chrono>
#include <thread>

class UsesDuration
{
public:
   UsesDuration( std::chrono::duration<double> dur ) :
      my_duration(dur) { }

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

   void somethingInteresting();

private:
   std::chrono::duration<double>  my_duration;
};

int
main()
{
    using namespace std::chrono_literals;
    UsesDuration x{5min};
}

chrono::duration . . , ( , ).

. , double , .

double

- , . <chrono>. , , .


, , <chrono>, .

. " ++ - , " <chrono>. . , . ++ 03, <chrono>. : ( ), , .

<chrono> :

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm

duration ( ) - , , . , , . , , .

- :

https://www.youtube.com/watch?v=P32hvk8b13M

+16

Source: https://habr.com/ru/post/1625365/


All Articles