从变量转换时std :: chrono :: time_point编译器错误

时间:2019-06-16 12:06:51

标签: c++ c++11 chrono

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

1 个答案:

答案 0 :(得分:4)

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