1

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’)"
jumho park
  • 15
  • 5

1 Answers1

2

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 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 – jumho park Aug 30 '19 at 02:29
  • 1
    It would be good to explain why `friend` makes a difference, rather than giving a code-only answer. – M.M Aug 30 '19 at 03:03
  • 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 Aug 31 '19 at 05:56
  • @Red.Wave what if i change accessibility of enum class to public? I've tested and it still needs ```friend``` . – jumho park Sep 01 '19 at 03:31
  • @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? – Red.Wave Sep 02 '19 at 05:00
  • @Red.Wave So it means ```friend``` grant accessibility to enum class to free function ```operator !``` of enum class! And this can inform compiler that it's not a memeber of class. Wow. – jumho park Sep 02 '19 at 14:48