我有几个enums定义如下:

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
};


对于这些enums中的每一个,我都重载了一些运算符:

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); }
// more overloads ...


请注意,两种类型的运算符重载的实现方式都是相同的。如何避免此代码重复?

我可以使用模板...

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


但是这些重载应仅适用于我的自定义类型。

最佳答案

您可以通过以下方式以可扩展的方式限制模板。

#include <type_traits>

template <class>
constexpr bool is_my_enum = false;       // most types are not my enums

enum class Suit {
    spades = 1, hearts, diamonds, clubs,
    first = spades, last = clubs
};
template<>
constexpr bool is_my_enum<Suit> = true;  // this is my enum

enum class Rank {
    six = 6, seven, eight, nine, ten, jack, queen, king, ace,
    first = six, last = ace
};
template<>
constexpr bool is_my_enum<Rank> = true;  // this one is mine too

enum class Moo { moo = 0 };              // but this one isn't



// define functions for my enums only
template<class T>
using for_my_enums = std::enable_if_t<is_my_enum<T>, T>;

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

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

// ... more functions ...


int main()
{
   Suit a = Suit::spades;
   ++a;                   // ok
   Moo b = Moo::moo;
   ++b;                   // compilation error, it's not my enum
}

关于c++ - 如何重用不同类型的运算符重载?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53973204/

10-14 20:17