Search code examples
c++operator-keywordfriendscope-resolution

Friends, operator keyword and scope resolution


namespace GameForge
{
    namespace Core
    {
        class CTribool;
    }
}

GameForge::Core::CTribool operator ! ( const GameForge::Core::CTribool& rkTribool );

namespace GameForge
{
    namespace Core
    {
        class CTribool
        {
            friend CTribool operator ! ( const CTribool& rkTribool );

        private:
            EState m_eState;
        };
    }
}


GameForge::Core::CTribool operator ! ( const GameForge::Core::CTribool& rkTribool )
{
    switch( rkTribool.m_eState )
        {
    // Some stuff...

Does not compile because m_eState is not accessible within the last definition. The reason is that the friend declaration occurs in the CTribool namespace and thus declares a different function. So i tried to use scope resolution operator as follow.

friend CTribool ::operator ! ( const CTribool& rkTribool );

and

friend CTribool ::( operator ! ) ( const CTribool& rkTribool );

But that doesn't work either because somehow CTribool is not recognized as a valid type. I suspect that the forward declaration is not enough in this case. Any work around ?


Solution

  • Strangely enough, you need to do this:

            friend CTribool (::operator !) ( const CTribool& rkTribool );
    

    You need to specify that your function is in global scope, but without the parentheses, your :: would bind with CTribool, as if you were doing this:

            friend (CTribool::operator !) ( const CTribool& rkTribool );
    

    in which case it would think you were specifying a function without a return type.