sunkue
sunkue

Reputation: 288

Is this correct to overwrite operator++ in enum_class?

enum class COLOR_
{
    RED,
    GREEN,
    BLUE,
    YELLOW,
    count
};
inline COLOR_& operator++(COLOR_& c) {
    c = static_cast<COLOR_>(static_cast<std::underlying_type<COLOR_>::type>(c) + 1);
    if (c == COLOR_::count) c = COLOR_::RED;
    return c;
};

this code is in my header file. I include that header to use (COLOR_)++;in main.cpp. and..

Error C2676
binary '++': 'COLOR_' does not define this operator or a conversion to a type acceptable to the predefined operator

this is the error. Tell me what am I missing or misundertanding.

Upvotes: 1

Views: 89

Answers (2)

Lukas-T
Lukas-T

Reputation: 11340

inline COLOR_& operator++(COLOR_& c) { ... }

Defines the pre-increment operator (++someColor). You can define the post-increment operator like this:

inline COLOR_ operator++(COLOR_ &c, int) {
    auto res = c;
    
    ++c;
    
    return res;
}

Upvotes: 2

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29965

Here's how you can implement pre and post increment and the wrapping behavior:

#include <type_traits>
#include <cassert>

enum class COLOR_
{
    RED,
    GREEN,
    BLUE,
    YELLOW,
    count
};

// Pre increment
COLOR_& operator++(COLOR_& c) {
    typedef std::underlying_type_t<COLOR_> ut;
    auto constexpr cnt = (ut)COLOR_::count;
    c = COLOR_(((ut)c+1)%cnt);
    return c;
};

// Post increment
COLOR_ operator++(COLOR_& c, int) {
    auto const copy = c;
    ++c;
    return copy;
};

int main() {
    COLOR_ c = COLOR_::RED;
    assert(c++ == COLOR_::RED);
    assert(c == COLOR_::GREEN);
    assert(++c == COLOR_::BLUE);
}

Upvotes: 2

Related Questions