我编写了一个通用计时器类,该计时器类使用std::chrono
时间。
这是一个显示该问题的代码示例:
#include <iostream>
#include <chrono>
template <typename Rep, typename TimeType>
class Timer {
public:
Timer(const std::chrono::duration<Rep, TimeType> timerLength);
~Timer() = default;
private:
std::chrono::duration<Rep, TimeType> _timerLength;
};
template <typename Rep, typename TimeType>
Timer<Rep, TimeType>::Timer(const std::chrono::duration<Rep, TimeType> timerLength) : _timerLength{timerLength} {}
int main()
{
constexpr int time_ms = 1000;
Timer timer(std::chrono::milliseconds(time_ms));
return 0;
}
此代码导致错误:
error: deduced class type ‘Timer’ in function return type
。可以通过将实际int直接放置在main中的计时器中来消除此错误:
Timer timer(std::chrono::milliseconds(1000));
此外,可以通过将
time_ms
参数转换为整数来消除此错误:Timer timer(std::chrono::milliseconds(`static_cast<int>(time_ms)));
我期望整数变量的结果相同,并将整数转换为整数。
无法通过删除
constexpr
变量的time_ms
来消除此错误。我的问题是:整数变量与将整数转换为整数(以及直接在
std::chrono::milliseconds()
中插入数字)之间有什么区别?为什么首先要有所作为?
最佳答案
您是令人烦恼的分析的受害者。使用-Wall
,clang甚至会发出警告
source>:24:16: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
Timer timer(std::chrono::milliseconds(time_ms));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
并提出修复建议。
<source>:24:17: note: add a pair of parentheses to declare a variable
Timer timer(std::chrono::milliseconds(time_ms));
^
( )
但是您也可以通过其他方式消除歧义。
Timer timer{std::chrono::milliseconds(time_ms)};
Timer timer(std::chrono::milliseconds{time_ms});
auto timer = Timer(std::chrono::milliseconds(time_ms));
Timer timer(static_cast<std::chrono::milliseconds>(time_ms));
以及在表达式中放入
int
文字,或显式转换为int
,您会注意到自己。
关于c++ - 整数变量与将整数转换为整数之间的结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60993069/