【问题标题】:std::chrono::time_point compiler error when converting from a variable从变量转换时出现 std::chrono::time_point 编译器错误
【发布时间】:2019-10-30 07:14:26
【问题描述】:

我有一个long long 类型的变量,它表示以纳秒为单位的时间点。

我正在尝试使用 std::chrono::time_point 来包装它,但编译器 (VS 2017) 给我带来了麻烦。

下面是编译的代码:

std::chrono::time_point<std::chrono::steady_clock> tpStart(std::chrono::nanoseconds(10ll));
std::chrono::time_point<std::chrono::steady_clock> tpEnd = std::chrono::steady_clock::now();
double d =  std::chrono::duration<double>(tpEnd - tpStart).count();

现在如果我用变量切换值10ll,计算持续时间的行编译失败:

constexpr long long t = 10ll;
std::chrono::time_point<std::chrono::steady_clock> tpStart(std::chrono::nanoseconds(t));
std::chrono::time_point<std::chrono::steady_clock> tpEnd = std::chrono::steady_clock::now();
double d =  std::chrono::duration<double>(tpEnd - tpStart).count();

这是错误代码:

错误 C2679:二进制“-”:未找到采用“重载函数”类型的右侧操作数的运算符(或没有可接受的转换)

知道为什么会这样吗?如何将 long long 类型的变量转换为 std::chrono::time_point?

【问题讨论】:

    标签: c++ c++11 chrono


    【解决方案1】:

    TLDR:这是most vexing parse 案例

    prog.cc:8:59: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
    std::chrono::time_point<std::chrono::steady_clock> tpStart(std::chrono::nanoseconds(t));
    

    {} 代替() 修复

    constexpr long long t = 10ll;
    std::chrono::time_point<std::chrono::steady_clock> tpStart{std::chrono::nanoseconds{t}};
    std::chrono::time_point<std::chrono::steady_clock> tpEnd = std::chrono::steady_clock::now();
    double d =  std::chrono::duration<double>(tpEnd - tpStart).count();
    

    为什么这是一个最令人头疼的解析?

    std::chrono::time_point<std::chrono::steady_clock> pStart  (std::chrono::nanoseconds(t));
    //                  ^^^^ Type 1 ^^^^^              ^name^      ^^^^ Type 2 ^^^^
    

    所以我们可以复制:

    constexpr long long t = 10ll;
    int fail (double (t) );
    fail = 6; // compilation error here
    

    为什么?让我们消除一些噪音:

    int fail (double (t) );
    //  <=> 
    int fail (double t);
    // <=>
    int fail (double) ; // Most vexing parse.
    

    我们可以通过切换到{}来修复它

    int Ok {double {t} };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-03
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 2013-05-14
      • 1970-01-01
      相关资源
      最近更新 更多