我正在将一些 C++ 代码移植到 Windows(来自 Linux/g++4.8.1),我注意到 Microsoft 对持续时间的模数运算符的实现是不正确的。
简单的程序
#include <chrono>
#include <iostream>
using namespace std::chrono;
int main(void)
{
std::cout << (milliseconds(1050)%seconds(1)).count() << std::endl;
return 0;
}
使用 Microsoft Visual Studio 2012 编译时出现编译错误:
error C2228: left of '.count' must have class/struct/union
标准 ( http://en.cppreference.com/w/cpp/chrono/duration/operator_arith4 ) 定义为
template< class Rep1, class Period1, class Rep2, class Period2 >
typename common_type<duration<Rep1,Period1>, duration<Rep2,Period2>>::type
constexpr operator%( const duration<Rep1,Period1>& lhs,
const duration<Rep2,Period2>& rhs );
即模数运算符返回通用类型的持续时间。 Microsoft 的实现 ( http://msdn.microsoft.com/en-us/library/hh874810.aspx ) 定义为
template<class Rep1, class Period1, class Rep2, class Period2>
constexpr typename common_type<Rep1, Rep2>::type
operator%(
const duration<Rep1, Period1>& Left,
const duration<Rep2, Period2>& Right);
这会错误地返回基础持续时间存储类型。这是一个错误,还是我遗漏了什么?
最佳答案
是的,this is a bug and the fix is available in Visual Studio 2015 .
它是实现错误的原因来自维度分析。
很明显,如果我们从 seconds
中减去 seconds
,结果就是 seconds
。
seconds = seconds - seconds
如果我们将 seconds
除以 seconds
,结果是一个标量(标量没有单位)。
scalar = seconds / seconds
最后,可以将 seconds
乘以一个标量,得到 seconds
。
seconds = seconds * scalar
seconds = scalar * seconds
在 [expr.mul]/p4 标准中定义了模运算符:
... if the quotient
a/b
is representable in the type of the result,(a/b)*b + a%b
is equal toa
...
略有不同:
a % b = a - (a/b)*b
因此 duration % duration
具有与以下相同的单位:
seconds - (seconds/seconds)*seconds
这简化为仅秒
,而不是标量。
同样的分析解释了原因:
seconds % scalar = seconds
关于visual-studio-2012 - Microsoft C++ 2012 中 std::chrono::duration::operator%() 的不符合返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17769172/