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

问题描述

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

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 友好度:

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

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{});
        }
    };
}

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

08-21 18:53