如何为枚举创建模板运算符

csb*_*ako 4 c++ templates enumeration enumerate c++11

我需要一个没有宏魔法的通用模板类,我可以像这样使用:

template<typename E>
class enum_operators
{
    E& operator++( E& orig )
    {
        orig = static_cast< E >( orig + 1 );
        return orig;
    }
};

enum colors : public enum_operators< colors >
{
    white,
    red,
    green,
    blue
};

enum corners : public enum_operators< corners >
{
    topleft,
    topright,
    bottomleft,
    bottomright
};
Run Code Online (Sandbox Code Playgroud)

是否可以使用可变参数模板或其他东西?我怎样才能做到这一点?

Que*_*tin 5

101010wowofbob的答案为基础:

template <class E, class = std::enable_if_t<std::is_enum<E>{}>>
E &operator ++ (E &e) {
    return e = static_cast<E>(
        static_cast<std::underlying_type_t<E>>(e) + 1
    );
}
Run Code Online (Sandbox Code Playgroud)

我已经SFINAE将操作员拿走了不是枚举的所有内容,并添加了正确的内容static_cast以便它也适用于enum classes.

住在Coliru

如果您不想授予所有enums在阳光下增加的能力,您可以将此运算符嵌套在命名空间中(比方说::incr_enum),然后您可以:

  • 按照101010建议在该命名空间中声明您的枚举,在这种情况下,通过ADL找到运算符;
  • using namespace incr_enum; 当您要在本地范围内导入和使用该运算符时.