cuốn sách gpt4 ai đã làm

c++ - 如何自动定义递增/递减/等运算符?

In lại Tác giả: Walker 123 更新时间:2023-11-28 03:22:31 29 4
mua khóa gpt4 Nike

我有一堆 liệt kê 类型,像这样:

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(c + 1);
trả lại c;
}

我还为习惯于使用 i++ thay vì ++i 编码循环的人们定义了后缀 operator++:

inline Color operator++(Color& c, int)
{
Color r = c;
c = static_cast(c + 1);
trả lại r;
}

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

以下是可行的,但在我看来太“强大”了:

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

我希望只为选定的枚举定义运算符。

câu trả lời hay nhất

以下应该可以帮助您入门,并根据需要进行扩展:

#include 

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 chính()
{
for( Foo foo = RED; foo != SIZE; ++foo ) {}
}

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

关于c++ - 如何自动定义递增/递减/等运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15051300/

29 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress