简体   繁体   English

为什么不能从C ++ 11中的非限定成员函数名称获取指向成员的指针?

[英]Why can't you get pointer-to-member from unqualified member function name in C++11?

The following code: 以下代码:

struct X
{
    void f() {}

    void g()
    {
        auto h = &f;
    }
};

results in: 结果是:

error: ISO C++ forbids taking the address of an unqualified
or parenthesized non-static member function to form a pointer
to member function.  Say ‘&X::f’

My question is, why is this not allowed and forbidden by the standard? 我的问题是, 为什么标准不允许和禁止这样做? It would be more convenient as a user to refer to it unqualified, so I assume there is some other rationale (safety? an ambiguity? ease of compiler implementation?) for the requirement? 作为用户,将它称为不合格会更方便,所以我假设有一些其他的理由(安全性?模糊性?编译器实现的简易性?)?

pointer-to-member is rare enough to allow special treatment and not necessarily the most economic one. 指向成员的指针非常罕见,可以进行特殊处理,而不一定是最经济的处理。 It was decided that the only accepted form is the one quoted in the error message. 决定唯一接受的形式是错误消息中引用的形式。 That form does not clash with anything else under any circumstances. 在任何情况下,这种形式都不会与其他任何形式发生冲突。 And prevents ambiguity of more lax forms were allowed. 并且可以防止更多松散形式的歧义。

Practice shows little awareness of PTMFs, and the fact they fundamentally differ from functions. 实践表明对PTMF的认识很少,而且它们与功能根本不同。 f or &f is likely a request for a normal function. f或&f可能是正常功能的请求。 One that can't be served for a nonstatic member. 一个不能为非静态成员服务的人。 And those who actually mean PTMF say so adding the &X:: part. 那些真正意味着PTMF的人说是这样添加&X :: part。

You're taking the address of a member function, not a function, and that means you will have to call it differently, too. 您正在获取成员函数的地址,而不是函数,这意味着您也必须以不同的方式调用它。

struct X
{
    void f() {}

    void g()
    {
        auto h = &X::f;
        h();
    }
};

Produces: 生产:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘h (...)’, e.g. ‘(... ->* h) (...)’

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM