如果传递变量,std :: chrono不起作用

时间:2014-09-05 13:46:24

标签: c++ c++11 std

我遇到了std :: chrono的奇怪错误, 如果我做这样的事情:

TimeHandling time(std::chrono::milliseconds(1000 / 125));
time.start();

一切都好。 但如果相反,我将毫秒值放在变量中:

int mpl = 1000 / 125;
TimeHandling time(std::chrono::milliseconds(mpl));
time.start();

g ++抛出此错误:

 request for member ‘start’ in ‘time’, which is of non-class type ‘TimeHandling(std::chrono::milliseconds) {aka TimeHandling(std::chrono::duration<long int, std::ratio<1l, 1000l> >)}’

有人知道为什么吗?

2 个答案:

答案 0 :(得分:5)

第二个版本使用名为mpl

的参数声明一个函数

请参阅http://en.wikipedia.org/wiki/Most_vexing_parsehttps://stackoverflow.com/tags/most-vexing-parse/info

C ++ 11允许您使用大括号来消除声明中的初始化:

TimeHandling time{std::chrono::milliseconds(mpl)};

或者,使用大括号进行两次初始化:

TimeHandling time{std::chrono::milliseconds{mpl}};

答案 1 :(得分:3)

这一行

TimeHandling time(std::chrono::milliseconds(mpl));

声明一个返回TimeHandling对象的函数,并取一个名为std::chrono::milliseconds的{​​{1}}参数。

当编译器面临将这种语句视为函数声明或构造函数调用的困境时,它(被标准)强制将其视为函数声明。

使用大括号初始化来纠正此问题并消除语句歧义。