3

Say I have this:

class Example {
    enum class E { elem1, elem2 };
    E& operator++(E& e) {
        // do things
    }
};

Seems to make perfect sense and I even see it used in other questions, but the compiler tells me that the parameters can only be either empty or an int.

This makes sense within a normal class, but exactly what am I supposed to operate on when I don't have a this value?

Community
  • 1
  • 1
idlackage
  • 2,715
  • 8
  • 31
  • 52
  • The question is not totally clear, can you reproduce live example using [Coliru](http://coliru.stacked-crooked.com/) or [Wandbox](http://melpon.org/wandbox) and produce a live example. – Shafik Yaghmour Nov 17 '15 at 02:47
  • @ShafikYaghmour http://ideone.com/tEmYxD It's basically just exactly what's in the question, but with the relevant error message. – idlackage Nov 17 '15 at 03:20
  • That is just incorrect, the operator is for class Example, if you take away the wrapping class then [it works fine](http://melpon.org/wandbox/permlink/cTf764hJC2suBsaC). Also returning a reference to a local variable is undefined behavior. – Shafik Yaghmour Nov 17 '15 at 03:26
  • I know that it works fine if one takes away the wrapping class, but I'm trying to define an operator for an enum inside that class--I don't get why it can't be done. Fixed the local variable thing, thanks. – idlackage Nov 17 '15 at 03:28
  • Define it outside the class [like so](http://melpon.org/wandbox/permlink/BT6p0V9iwRHFvtna) – Shafik Yaghmour Nov 17 '15 at 03:42
  • I see now, seems kind of roundabout but thanks. Can you make your comment an answer so that I can accept it? – idlackage Nov 17 '15 at 03:51

2 Answers2

3

The operator you defined inside the class applies to the class Example and therefore having an argument and return type of E& is incorrect and the compiler tells you so.

The standard tell us that:

An operator function shall either be a non-static member function or be a non-member function[...]

it can't be a non-static member function of E therefore it has to be a non-member function.

You can define the operator outside of Example as follows:

Example::E& operator++(Example::E& e) {
    // modify e
    return e ;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • What if `E` is a private enum (as in the original question), used solely within the `Example` class? Does that mean that C++ doesn't have a way how to define an operator in such case? (that would be quite surprising...) – Miro Kropacek Jan 28 '23 at 19:23
0

As @Shafik answered you can declare operator for an enum that is declared inside of class only as non-member function, like here:

class Example 
{
public:
    enum class Element
    { 
        Element1, 
        Element2
    };
};

Example::Element operator++(Example::Element element)
{
     // do things
}

There is a nice post regarding implementation of increment operator for enums. Hope it will help you :)

Community
  • 1
  • 1
metal4people
  • 131
  • 2
  • 5