Is it possible to use std::chrono::duration with R

2019-08-06 17:28发布

问题:

I get a following compiler (vs2012) error:

Error 3 error C2679: binary '+=' : no operator found which takes a right-hand operand of type 'const std::chrono::duration<_Rep,_Period>' (or there is no acceptable conversion) c:\program files (x86)\microsoft visual studio 11.0\vc\include\chrono 749

My definition of duration is:

// Tick interval type in nanoseconds
typedef std::chrono::duration<double, std::ratio<1, 100000000>> tick_interval_type;

Same error when I use float... It only compiles when the Rep type of duration is integer.

Can someone please help?

Edit (more complete log from Output):

c:\program files (x86)\microsoft visual studio 11.0\vc\include\chrono(749): error C2679: binary '+=' : no operator found which takes a right-hand operand of type 'const std::chrono::duration<_Rep,_Period>' (or there is no acceptable conversion) with [ _Rep=double, _Period=std::nano ] c:\program files (x86)\microsoft visual studio 11.0\vc\include\chrono(166): could be 'std::chrono::duration<_Rep,_Period> &std::chrono::duration<_Rep,_Period>::operator +=(const std::chrono::duration<_Rep,_Period> &)' with [ _Rep=__int64, _Period=std::nano ] while trying to match the argument list '(std::chrono::nanoseconds, const std::chrono::duration<_Rep,_Period>)' with [ _Rep=double, _Period=std::nano ] c:\program files (x86)\microsoft visual studio 11.0\vc\include\thread(164) : see reference to function template instantiation 'xtime std::_To_xtime(const std::chrono::duration<_Rep,_Period> &)' being compiled with [ _Rep=double, _Period=std::nano ] c:\dev\projects\revolverx\classes\ticker.h(78) : see reference to function template instantiation 'void std::this_thread::sleep_for(const std::chrono::duration<_Rep,_Period> &)' being compiled with [ _Rep=double, _Period=std::nano ]

回答1:

<chrono> in Visual Studio is broken. It doesn't work with mixed type arithmetic, which, arguably, is one of the main features of <chrono>. You get this error because one of the sides uses __int64 nanos and the other uses double nanos.

I recommend either dropping it in favor of a real C++ implementation, or using Boost.Chrono.



回答2:

Update: I've come upon this question four years after it was originally posted, and I've tested this on Visual Studio 2015. It does compile now. For example:

#include <iostream>
#include <iomanip>
#include <chrono>

int main()
{
    typedef std::chrono::duration<double, std::ratio<1, 100000000>> tick_interval_type;  // Originally posted line
    tick_interval_type tick {0};
    tick += std::chrono::microseconds(3);
    std::cout << std::setprecision(6) << std::fixed << tick.count();
    return 0;
}

Output:

300.000000