2

I'm using private enum class in nested class and want to implement operator! for my enum class.

I know how to do this. But when I tried to overlord operator of enum class in nested class, compiler treats my operator as an operator of class, not for enum class.

class test{
    private:
        enum class Loc : bool{
            fwrd = true,
            bkrd = false
        };

        Loc Loc::operator!(){        //error msg 1.
             return Loc(!bool(*this));
        }

        Loc operator!(){
             return something;       //this treated as test's operator
        }


        Loc doSomething(Loc loc){
             return !loc;            //error msg 2.
        }


}

enum class Other : bool{
    fwrd = true,
    bkrd = false
};
Other operator!(Other o){                //this works
    return Other(!bool(*this));
}

Error msgs

  1. "enum class test::Loc is not a class or a namespace.".
  2. "no match for ‘operator!’ (operand type is ‘test::Loc’)"
1
  • @Jarod42 Oops! my mistake. edited Commented Aug 30, 2019 at 2:17

1 Answer 1

4

You might use friend functions:

class test
{
private:

    enum class Loc : bool{
        fwrd = true,
        bkrd = false
    };
    friend Loc operator!(Loc loc){
         return Loc(!bool(loc));
    }
    Loc doSomething(Loc loc){
         return !loc;
    }
};

Demo

Sign up to request clarification or add additional context in comments.

6 Comments

wow it works... But i can't understand why 'friend' can solve this probelm. All that i know about 'friend' is 'friend function' or 'friend class', which giving access to others
It would be good to explain why friend makes a difference, rather than giving a code-only answer.
enum cannot have member functions, so you gotta define the operator as a free function; but it has to access private member of class 'test', hence the freind declaration is needed. On the other hand for the sake of readability and avoiding dealing with probable namespace details, the function is defined within the class - resulting in ADL doing the rest.
@Red.Wave what if i change accessibility of enum class to public? I've tested and it still needs friend .
@jumhopark The free function('operator !' in this case) is normally defined at namespace scope. But when one defines a free function inside a class, there is no other way to inform the compiler that it is not a member; hence you need the 'freind' spec. Did you try defining the function outside the class?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.