【发布时间】:2019-07-16 16:54:42
【问题描述】:
如std::chrono::duration::operator+= 中所述,签名是
duration& operator*=(const rep& rhs);
这让我很奇怪。我会假设持续时间文字可以像任何其他内置函数一样使用,但事实并非如此。
#include <chrono>
#include <iostream>
int main()
{
using namespace std::chrono_literals;
auto m = 10min;
m *= 1.5f;
std::cout << " 150% of 10min: " << m.count() << "min" << std::endl;
int i = 10;
i *= 1.5f;
std::cout << " 150% of 10: " << i << std::endl;
}
输出是
150% of 10min: 10min
150% of 10: 15
为什么要这样选择界面?在我看来,像
这样的界面template<typename T>
duration& operator*=(const T& rhs);
会产生更直观的结果。
编辑:
感谢您的回复,我知道实现的行为方式以及我如何处理它。我的问题是,为什么是这样设计的。
我希望在操作结束时转换为 int。在以下示例中,在乘法发生之前,两个操作数都被提升为 double。 4.5的中间结果之后再转成int,这样结果就是4。
int i = 3;
i *= 1.5;
assert(i == 4);
我对 std::duration 的期望是它的行为方式相同。
【问题讨论】:
-
rep 是
an arithmetic type representing the number of ticks,分钟是/*signed integer type of at least 29 bits*/,而不是float。 -
POD在这里不是正确的术语。您的意思可能是“内置”。 -
除了术语,我 100% 同意
template <class T> duration& operator*=(const T& rhs);版本会更直观。例如int i = 10; i *= 1.5;也导致i == 15,我想知道为什么这里没有遵循“自定义类型应该像内置类型一样可用”的 C++ 教条。