Search code examples
c++operator-overloadinginner-classesenum-class

Operator overloading of enum class in class


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’)"

Solution

  • 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