samedi 29 décembre 2018

How to reuse operator overloads for different types?

I have several enums defined as follows:

enum class Suit {
    spades = 1, hearts, diamonds, clubs,
    first = spades, last = clubs
};

enum class Rank {
    six = 6, seven, eight, nine, ten, jack, queen, king, ace,
    first = six, last = ace
};

For each of these enums I have overloaded some operators:

Suit operator++(Suit& r) { return r = (Suit)(static_cast<std::underlying_type_t<Suit>>(r) + 1); }
Rank operator++(Rank& r) { return r = (Rank)(static_cast<std::underlying_type_t<Rank>>(r) + 1); }
// [...] lots of code duplication for other operators...

Note that the implementation of the operator overloads is the same for both types. How can I avoid this code duplication?

I could use templates...

template<class T>
T operator++(T& r) { return r = (T)(static_cast<std::underlying_type_t<T>>(r) + 1); }

but these overloads should apply to my custom types only.

Aucun commentaire:

Enregistrer un commentaire