如何自动定义递增/递减等运算符

How to define increment/decrement/etc operator automatically?

本文关键字:运算符 何自动 定义      更新时间:2023-10-16

我有一堆enum类型,如下所示:

enum Color {COLOR_RED = 0, COLOR_GREEN = 1, COLOR_BLUE = 2, COLOR_NUM};
enum Direction {DIRECTION_FORWARD, DIRECTION_BACKWARD, DIRECTION_NUM};
enum Choice {CHOICE_THIS, CHOICE_THAT, CHOICE_NUM}; // i've just made it up

在我的代码中的许多地方,我希望对所有可能的值进行循环;我希望它看起来像这样:

for (Color c = COLOR_RED; c != COLOR_NUM; ++c)
{
    ...
}

为此,我将operator++Color:一起定义

enum Color {COLOR_RED = 0, COLOR_GREEN = 1, COLOR_BLUE = 2, COLOR_NUM};
inline Color& operator++(Color& c)
{
    c = static_cast<Color>(c + 1);
    return c;
}

我还为那些习惯于用i++而不是++i编码循环的人定义了后缀operator++

inline Color operator++(Color& c, int)
{
    Color r = c;
    c = static_cast<Color>(c + 1);
    return r;
}

我想知道如何使用模板让编译器生成这些运算符,而不必编写太多无聊的代码。我刚刚找到了boost::unit_steppable,它应该根据前缀1生成后缀operator++,但它只完成了一半的工作:我仍然需要自己提供前缀operator++

以下作品,但在我看来过于"强大":

template <class T> T operator++(T x)
{
    return static_cast<T>(x + 1);
}

我希望只为选定的enum s定义运算符。

以下内容应该会让您开始,并根据需要进行扩展:

#include <type_traits>
enum Foo { RED, GREEN, BLUE, SIZE };
template< typename T > struct my_enum_is_unit_steppable { enum { value = false }; };
// for each type you want the operator(s) to be enabled, do this:
template<> struct my_enum_is_unit_steppable< Foo > { enum { value = true }; };
// protect the operators with enable_if
template< typename T >
typename std::enable_if< my_enum_is_unit_steppable< T >::value, T >::type
operator++( T value )
{
    return T( value + 1 );
}
int main()
{
    for( Foo foo = RED; foo != SIZE; ++foo ) {}
}

当然,这使用了C++11的std::enable_if,但Boost有C++03版本可用。