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

Different results between an integer variable and casting an integer to an integer

我编写了一个通用计时器 class,它使用计时器的 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

可以通过在 main 的定时器中直接放置一个实际的 int 来消除这个错误:

Timer timer(std::chrono::milliseconds(1000));

此外,可以通过将 time_ms 参数转换为整数来消除此错误:

Timer timer(std::chrono::milliseconds(`static_cast<int>(time_ms)));

我期望整数变量和将整数转换为整数的相同结果。

无法通过删除 time_ms 变量的 constexpr 来删除此错误。

我的问题是:整数变量和将整数转换为整数(以及直接在 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,正如您自己注意到的那样。