我正在学习 C++11,我偶然发现了统一初始化程序.
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;
}
这里:
auto dv = Timer();
您有一个名为 dv
的 Timer
类型的对象,它正在从临时对象(=
右侧的表达式)复制初始化代码> 符号).
You have an object of type Timer
called dv
that is being copy-initialized from a temporary (the expression on the right side of the =
sign).
当使用 auto
声明一个变量时,该变量的类型与初始化它的表达式的类型相同——这里不考虑 cv 限定符和引用.
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.
在您的情况下,初始化 dv
的表达式的类型为 Timer
,因此 dv
的类型为 Timer
.
In your case, the expression that initializes dv
has type Timer
, and so dv
has type Timer
.
这里:
int time_keeper(Timer());
您声明了一个名为 time_keeper
的函数,它返回一个 int
并将指针作为它的输入,该函数返回一个 定时器
,不带参数.
You declare a function called time_keeper
that returns an int
and takes as its input a pointer to a function which returns a Timer
and takes no argument.
为什么不是参数 Timer (*) ()
?
当作为参数传递时,函数衰减为指针,所以time_keeper
的类型实际上是int(Timer(*)())
.
Functions decay to pointers when passed as an argument, so the type of time_keeper
is actually int(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!");
}
这里有一个referar">noliver>>.
Here is a live example.
这篇关于最令人头疼的解析混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!