【问题标题】:Different results between an integer variable and casting an integer to an integer整数变量和将整数转换为整数之间的不同结果
【发布时间】:2020-04-02 13:47:18
【问题描述】:

我编写了一个通用计时器类,它使用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())之间有什么区别?为什么它首先会有所作为?

【问题讨论】:

  • 这能回答你的问题吗? Most vexing parse
  • {} 将把你从最烦人的解析中拯救出来:Timer timer{std::chrono::milliseconds(time_ms)}

标签: c++ templates int chrono


【解决方案1】:

你是一个令人烦恼的解析的受害者。 -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,正如您自己注意到的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2019-06-12
    • 2011-12-10
    • 1970-01-01
    • 2011-10-05
    相关资源
    最近更新 更多