c++ - 整数变量与将整数转换为整数之间的结果不同

标签 c++ templates int chrono

我编写了一个通用计时器类,该计时器类使用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/

相关文章:

c++ - 在 C++ 中实现无序映射

c++ - std::set(红/黑树)前向迭代是如何实现的?

Spring Freemarker配置,未找到模板

c - 在 c 中,sizeof()..[-1] 是什么意思

C++:OpenCV 扫描图像的性能问题

c++ - 哪个 C++ XSLT 处理器?

c++ - 编译类型模板谓词使用 Clang 进行编译,但不使用 GCC 或 MSVC

json - 带有 Handlebars 模板的嵌套 {{each}} 循环

ios - 释放一个整数?

java - LayoutInflater 类型中的方法 inflate(int, ViewGroup, boolean) 不适用于参数 (int, int, boolean)