如何调用与成员函数同名的内联好友函数? [英] how do I call an inline friend function with the same name as a member function?

查看:113
本文介绍了如何调用与成员函数同名的内联好友函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如此处所述 C ++ 11样式SFINAE和模板实例化上的函数可见性类成员函数使无用函数蒙上阴影。通常使用完全限定的名称是可行的,但是我很难与其他内联声明的类的朋友函数一起使用。考虑下面的示例:

As described here C++11 style SFINAE and function visibility on template instantiation class member functions overshadow free functions. Using a fully qualified name usually works, however I am having a hard time with friend functions of other classes which are declared in-line. Consider the following example:

namespace N {

    struct C {
        friend int f(const C& c) {
            return 1;
        }
        friend int g(const C& c) {
            return 2;
        }
    };

    struct D {
        void f() {
            g(C{});            // ADL finds this
            ::N::f(C{});       // not found dispite full qualification
        }
    };
}

我想我理解问题所在,如此处所述内联朋友功能的范围是什么?内联朋友功能通常使用ADL而不是在封闭的名称空间中真正可见。

I think I understand what the problem is, as described here What's the scope of inline friend functions? inline friend function are usually found using ADL and not really visible in the enclosing namespace.

所以我的问题是我应该如何更改代码以使其正常工作(除了重命名f中的一个)?

So my question is how should I change my code to make this work (aside from renaming one of the f's)?

推荐答案

这是因为 friend 友好度:


[C ++ 11:7.3.1.2/3]:如果在非-local类首先声明一个类或函数,而该朋友类或函数是最内部封闭的命名空间的成员。 在命名空间范围内提供匹配的声明之前,无法通过简单的名称查找找到朋友的名字 [...] 。如果调用了朋友函数,则可以通过名称查找来找到其名称,该名称查找考虑了与函数自变量类型相关联的名称空间和类中的函数(3.4.2) [即ADL]

[C++11: 7.3.1.2/3]: If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by simple name lookup until a matching declaration is provided in that namespace scope [...]. If a friend function is called, its name may be found by the name lookup that considers function from namespaces and classes associated with the types of the function arguments (3.4.2) [i.e. ADL].

解决方法是简单地提供该声明:

The fix is to simply provide that declaration:

namespace N {

    struct C {
        friend int f(const C& c) {
            return 1;
        }
        friend int g(const C& c) {
            return 2;
        }
    };

    int f(const C& c);
    int g(const C& c);

    struct D {
        void f() {
            g(C{});
            ::N::f(C{});
        }
    };
}

这篇关于如何调用与成员函数同名的内联好友函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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