Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::chrono: add custom duration to time_point

Tags:

c++

chrono

The following code does compile (g++ 4.7.2):

#include <chrono>

typedef std::chrono::duration< double > double_prec_seconds;
typedef std::chrono::time_point< std::chrono::system_clock > timepoint_t;

void do_something( const timepoint_t& tm )
{
    // ...
}

int main( int argc, char** argv )
{
    timepoint_t t0 = std::chrono::system_clock::now();
    timepoint_t t1 = t0 + std::chrono::seconds(3);

    // timepoint_t t3 = t0 + double_prec_seconds(3.14);
   auto t3 = t0 + double_prec_seconds(3.14);

    do_something( t1 );
}

My problem is that I don't know what type t3 has. It's not timepoint_t, and un-commenting the line with the type explicitely given would not compile. The same with the function call: I can't call do_something with t3.

So my questions are:

  • Why does the conversion fail?
  • What's the best way to have double precision seconds durations?

I know that I can use an additional cast like this

// this works
timepoint_t t3 = t0 + std::chrono::duration_cast< std::chrono::milliseconds >(double_prec_seconds(3.14));

but I want to avoid this.

Thank you in advance!

like image 961
wal-o-mat Avatar asked Feb 24 '13 13:02

wal-o-mat


1 Answers

The conversion fails, because there is no conversion from

std::chrono::time_point< std::chrono::system_clock,
                         std::chrono::system_clock::duration >

to

std::chrono::time_point< std::chrono::system_clock,
                         std::chrono::duration< double > >

The easiest way would be to give double_prec_seconds as a template parameter to time_point, see std::chrono::time_point

typedef std::chrono::time_point< std::chrono::system_clock,
                                 double_prec_seconds > timepoint_t;

then you already have the proper type for t3 and do_something.

like image 82
Olaf Dietsche Avatar answered Oct 23 '22 12:10

Olaf Dietsche