如何自动定义递增/递减等运算符
How to define increment/decrement/etc operator automatically?
我有一堆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版本可用。
相关文章:
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 删除了所有自动生成的构造函数/运算符的类仍然可以从函数返回吗
- 如何在C++中自动生成运算符=?
- 如何使用 boost/operator.hpp 自动生成 == 运算符?
- C++对自动(堆栈)指针使用运算符删除
- 未自动确定模板化的隐式转换运算符
- 使用 std::function 时选择自动返回类型而不是构造函数的调用运算符
- 过载输入运算符未通过自动简单输入测试
- 为什么C++不使用运算符==而不是运算符!=自动
- 模板类自动类型转换的运算符重载
- 自动与三元运算符和模板
- 通过具有重载运算符函数的构造函数自动进行类型转换
- 绕过自动生成的赋值运算符(VS 错误?
- 为结构/类自动生成流运算符
- Visual Studio 2013 - 自动插入"->"运算符
- C++ 模板运算符重载上的自动构造函数调用
- C++是运算符!=定义运算符==时自动提供
- 如何自动定义递增/递减等运算符
- 如何使用std::relops自动提供比较运算符
- 是否可以在结构外部编写自动转换运算符