c++ - 从变量转换时出现 std::chrono::time_point 编译器错误

标签 c++ c++11 c++-chrono most-vexing-parse

我有一个 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?

最佳答案

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} };

关于c++ - 从变量转换时出现 std::chrono::time_point 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56618678/

相关文章:

c++ - 为什么 CLS() 在 C++11 中有不同的含义

c++ - 方法冗余 move 调用的 move 语义

c++ - 在循环中使用 std::list 的删除方法会创建段错误

c++ - std::move 更改变量地址?

c++ - 如何在 C++ 中以毫秒为单位输出时间?

c++ - 在 Dev C++ 中运行一个项目

c++ - 在代码块中调试时如何查看数组的内容?

c++ - 从 C++ "time.h"测量的运行时间是实际运行时间的两倍

c++ - duration_cast 怎么轮

c++ - 将 chrono::duration 类型转换为 std::tm 类型