Search code examples
c++qtfriendforward-declaration

forward declaration of global friend function


I have the following namespaces and classes hierarchy:

namespace Ns1 {
    class Outer {
    private:
           class Inner {
           };
           QSet<Inner> set;
    };
}

Now I need to declare a global functions:

uint qHash(Ns1::Outer::Inner const& el);
bool operator==(Ns1::Outer::Inner const& el1,
                Ns1::Outer::Inner const& el);

So the function must be a friend to Outer and Inner. The problem and to show that the function is in global scope:

friend uint qHash(Ns1::Outer::Inner const& el);
friend operator==(Ns1::Outer::Inner const& el1,
                Ns1::Outer::Inner const& el);

I can't deal with forward declarations for this case. Any solutions?


Solution

  • EDIT:

    You're right! You've found a corner case that the language just can't handle (because friendship declarations only apply to previously declared functions or else to the innermost namespace). Unfortunately this means you're going to have to slightly restructure your code, as what you want to do can't be done in exactly that way.

    The simplest approach is to define the two functions in the Ns1 namespace and then using them into the global namespace. This has basically the exact same effect as what you want except there are two extra functions in the nested namespace.

    Your other set of options involves addressing the problem at its root: Why do your class objects' public interface not provide an adequate capability such that friendship is needed? For example, why is Inner private within Outer if you're intended to be able to pass around Inner objects at global scope?

    Why do hash and compare functions need access to Inner's internal state? Why not have Inner provide a public comparison interface that's then utilized by the operators?