为什么类成员函数影子使用相同名称的自由函数? [英] Why class member functions shadow free functions with same name?

查看:196
本文介绍了为什么类成员函数影子使用相同名称的自由函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近来到我的注意,成员函数完全 在类中有相同名称的自由函数。而完全地,我的意思是每个自由功能具有相同的名称不考虑重载分辨率。我可以理解为什么它做这样的事情:

It recently came to my attention that member functions completely shadow free functions with the same name when inside the class. And by completely i mean that every free function with the same name is not considered for overload resolution at all. I can understand why it's done with somwthing like this:

void f();

struct S
{
    void f();

    void g()
    {
        f(); // calls S::f instead of ::f
    }
};

其中函数具有相同的签名,其唯一自然的变量范围工作方式相同。但为什么禁止unbigious调用,其中自由函数有不同的签名,如下:

where the functions have identical signatures, its only natural as variable scoping works the same way. But why prohibit unambigious calls where free function has different signature like this:

void f();

struct S
{
    void f(int x);

    void g()
    {
        f(); // fails to compile attempting to call S::f, which has wrong signature
    }
};

我不是在询问如何调用类。我想知道的是这个设计背后的理由。

I am not asking how to call a shadowed free function from inside the class. What i want to know is the rationale behind this design.

推荐答案

对于非限定名称查找,一次只能考虑一个范围,如果该范围内的搜索不产生任何结果,下一个较高的范围被搜索。在你的情况下,只搜索 S 的范围。

For unqualified name lookup, only one scope at a time is considered, and if the search in that scope doesn't yield any results, the next higher scope is searched. In your case, only S's scope is searched.


unbigious调用,其中自由函数具有不同的签名,如下:

But why prohibit unambigious calls where free function has different signature like this:

问题是名称查找只关心名称​​标识符。这是完全不知道的事实,你想调用一个函数,它只是看到一个标识符。如果你只是使用 auto x = f; ,如果你这样想,同样的名称查找发生,有很好的理由你只想要一个非常有限的范围搜索。其他任何事情只会让用户惊喜。

The problem is that name lookup doesn't concern itself with anything but the name, the identifier. It is completely oblivious to the fact that you want to call a function, it just sees an identifier. The same name lookup happens if you just use auto x = f;, and if you think of it that way, there are very good reasons you only want a very limited scope to search. Anything else would just surprise the user.

这篇关于为什么类成员函数影子使用相同名称的自由函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆