C++11 c++;11计时条件语句
请有人描述一下下面的代码好吗C++11 c++;11计时条件语句,c++11,chrono,C++11,Chrono,请有人描述一下下面的代码好吗 template<typename _Rep2, typename = typename enable_if<is_convertible<_Rep2, rep>::value && (treat_as_floating_point<rep>::value || !treat_as_floating_point<_Rep2>::value)>
template<typename _Rep2, typename = typename
enable_if<is_convertible<_Rep2, rep>::value
&& (treat_as_floating_point<rep>::value
|| !treat_as_floating_point<_Rep2>::value)>::type>
constexpr explicit duration(const _Rep2& __rep)
: __r(static_cast<rep>(__rep)) { }
template<typename _Rep2, typename _Period2, typename = typename
enable_if<treat_as_floating_point<rep>::value
|| (ratio_divide<_Period2, period>::den == 1
&& !treat_as_floating_point<_Rep2>::value)>::type>
constexpr duration(const duration<_Rep2, _Period2>& __d)
: __r(duration_cast<duration>(__d).count()) { }
模板
constexpr显式持续时间(const_Rep2和_rep)
:uu r(静态_cast(u rep)){}
模板
constexpr持续时间(const duration&uud)
:uu r(持续时间\u转换(u d).count()){}
这些是std::chrono::duration
构造函数的gcc/libstdc++实现。我们可以一次看一个:
template <typename _Rep2,
typename = typename enable_if
<
is_convertible<_Rep2, rep>::value &&
(treat_as_floating_point<rep>::value ||
!treat_as_floating_point<_Rep2>::value)
>::type>
constexpr
explicit
duration(const _Rep2& __rep)
: __r(static_cast<rep>(__rep))
{ }
这将不会编译,因为minutes
是基于整数的,并且参数是浮点,如果它编译了,它将自动放弃.5
,从而导致1min
现在来看第二个chrono::duration
构造函数:
template <typename _Rep2,
typename _Period2,
typename = typename enable_if
<
treat_as_floating_point<rep>::value ||
(ratio_divide<_Period2, period>::den == 1 &&
!treat_as_floating_point<_Rep2>::value)
>::type>
constexpr
duration(const duration<_Rep2, _Period2>& __d)
: __r(duration_cast<duration>(__d).count())
{ }
第一个示例没有编译,因为它需要除以60,结果是h
不等于30min
。但是第二个例子编译是因为m
正好等于1h
(它将保持60min
)
您可以从中获得什么:
为您进行转换。如果在代码中用60或1000(或其他)进行乘法或除法运算,那么就不必要地引入了错误的可能性。此外,如果您将所有转换委托给
,则
会让您知道是否有任何有损转换
转换。它们要么编译并精确,要么不编译。如果它们不编译,这意味着您请求的转换涉及截断错误。请求截断错误是可以的,只要您不意外地这样做。请求截断转换的语法为:
hours h = duration_cast<hours>(30min); // ok, h == 0h
h小时=持续时间(30分钟);//好的,h==0h
我们不知道你想从这个问题中得到什么。代码有问题吗?你到底想让我们解释一下这个代码吗?没有人有时间写一个完整的分析。非常感谢。很好的解释。
hours h = 30min; // will not compile
minutes m = 1h; // ok
hours h = duration_cast<hours>(30min); // ok, h == 0h