成员函数指针的奇怪C ++规则? [英] Strange C++ rule for member function pointers?
问题描述
可能重复:
包含成员函数地址的错误
在这个最近的问题中,OP遇到了一个奇怪的C ++语言配置,使它非法以获取成员函数的地址(如果该成员函数名称带括号)。例如,此代码是非法的:
In this recent question the OP ran into a strange provision of the C++ language that makes it illegal to take the address of a member function if that member function name is parenthesized. For example, this code is illegal:
struct X {
void foo();
};
int main() {
void (X::* ptr)();
ptr = &(X::foo); // Illegal; must be &X::foo
}
我看了一下,发现由于C ++ ISO规范的§5.3.1/ 3,它读取
I looked this up and found that it's due to §5.3.1/3 of the C++ ISO spec, which reads
指向成员的指针只有在显式& [...]
A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses [...]
有没有人知道为什么规范有这个规则吗?它特定于指向成员的指针,所以我怀疑有一些语法歧义,这个解决,但我真的没有最昏暗的想法它可能是什么。
Does anyone have any idea why the spec has this rule? It's specific to pointers-to-member, so I would suspect that there is some grammatical ambiguity that this resolves, but I honestly haven't the faintest idea what it might be.
推荐答案
这只是一个个人意见。
如果&(unary-expression)
允许&(qualified-id)
b $ b qualified-id必须是一个表达式,并且表达式应该具有类型
(即使它不完整)。
然而,C ++没有表示成员的类型,只有
是指向成员的指针。
例如,以下代码不能编译。
This is just a personal opinion.
If &(qualified-id)
is allowed as &(unary-expression)
,
qualified-id has to be an expression, and an expression is expected to have a type
(even if it is incomplete).
However, C++ didn't have a type which denotes a member, had only
a pointer to member.
For example, the following code cannot be compiled.
struct A { int i; };
template< class T > void f( T* );
int main() {
(void) typeid( A::i );
f( &A::i );
}
为了使& )
有效,编译器必须在内部持有
a成员类型。
然而,如果我们放弃&(qualified-id)
符号,编译器不需要
来处理成员类型。
作为成员类型总是以指向它的指针的形式处理,
我想标准优先简化编译器的类型
系统一点。
In order to make &(qualified-id)
be valid, the compiler has to hold
a member type internally.
However, if we abandon &(qualified-id)
notation, the compiler doesn't need
to handle member type.
As member type was always handled in the form of a pointer to it,
I guess the standard gave priority to simplify the compiler's type
system a little.
这篇关于成员函数指针的奇怪C ++规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!