最烦躁的解析混乱 [英] Most vexing parse confusion
问题描述
我正在学习C ++ 11,我偶然发现了统一的初始化器。
我不明白下面的代码应该显示最烦琐的解析歧义:
#include< iostream>
class Timer
{
public:
Timer(){}
};
int main()
{
auto dv = Timer(); //什么是Timer()?什么类型是dv?
int time_keeper(Timer()); //这是一个函数对吗?为什么不是参数Timer(*)()?
return 0;
}
auto dv = Timer();
您有一个类型为 Timer
的对象 =
符号右侧的表达式)复制初始化的 dv
/ p>
使用 auto
声明变量时,该变量的类型与表达式的类型相同初始化它 - 不考虑cv限定符和引用。
在您的情况下,初始化 dv
的表达式类型为 Timer
,因此 dv
有类型 Timer
。
这里:
int time_keeper
您声明一个名为 time_keeper
int
,并将指针作为其输入,返回 Timer
没有参数。
为什么不是参数
Timer(*)()
?
函数在作为参数传递时衰减指针,因此 time_keeper
实际上是 int(Timer(*)()
。
编译这个小程序:
#include< type_traits>
/ pre>
struct Timer {};
int main()
{
int time_keeper(Timer());
static_assert(
std :: is_same<
decltype(time_keeper),
int(Timer(*)())
> :: value,
这不应该启动!);
}
这里是 生活示例 。
I'm studying C++11 and I stumbled upon uniform initializers.
I don't understand the following code which should show the "most vexing parse" ambiguity:
#include<iostream> class Timer { public: Timer() {} }; int main() { auto dv = Timer(); // What is Timer() ? And what type is dv? int time_keeper(Timer()); // This is a function right? And why isn't the argument " Timer (*) ()" ? return 0; }
解决方案Here:
auto dv = Timer();
You have an object of type
Timer
calleddv
that is being copy-initialized from a temporary (the expression on the right side of the=
sign).When using
auto
to declare a variable, the type of that variable is the same as the type of the expression that initializes it - not considering cv-qualifiers and references here.In your case, the expression that initializes
dv
has typeTimer
, and sodv
has typeTimer
.Here:
int time_keeper(Timer());
You declare a function called
time_keeper
that returns anint
and takes as its input a pointer to a function which returns aTimer
and takes no argument.And why isn't the argument
Timer (*) ()
?Functions decay to pointers when passed as an argument, so the type of
time_keeper
is actuallyint(Timer(*)()
.To convince yourself, you could try compiling this little program:
#include <type_traits> struct Timer { }; int main() { int time_keeper(Timer()); static_assert( std::is_same< decltype(time_keeper), int(Timer(*)()) >::value, "This should not fire!"); }
Here is a live example.
这篇关于最烦躁的解析混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!