如何在作用域枚举上重载| =运算符? [英] How to overload |= operator on scoped enum?
问题描述
如何在强类型(作用域)enum
(在C ++ 11,GCC中)上重载|=
运算符?
我想测试,设置和清除强类型枚举上的位.为什么要强打?因为我的书说这是一种好习惯.但这意味着我必须在任何地方都static_cast<int>
.为了防止这种情况,我重载了|
和&
运算符,但是我不知道如何在枚举中重载|=
运算符 .对于一个类,您只需将该操作符定义放在该类中,但是对于似乎在语法上不起作用的枚举
I want to test, set and clear bits on strongly typed enums. Why strongly typed? Because my books say it is good practice. But this means I have to static_cast<int>
everywhere. To prevent this, I overload the |
and &
operators, but I can't figure out how to overload the |=
operator on an enum. For a class you'd simply put the operator definition in the class, but for enums that doesn't seem to work syntactically.
这是我到目前为止所拥有的:
This is what I have so far:
enum class NumericType
{
None = 0,
PadWithZero = 0x01,
NegativeSign = 0x02,
PositiveSign = 0x04,
SpacePrefix = 0x08
};
inline NumericType operator |(NumericType a, NumericType b)
{
return static_cast<NumericType>(static_cast<int>(a) | static_cast<int>(b));
}
inline NumericType operator &(NumericType a, NumericType b)
{
return static_cast<NumericType>(static_cast<int>(a) & static_cast<int>(b));
}
我这样做的原因:这就是它在强类型C#中的工作方式:一个枚举中只有一个结构及其基础类型的字段以及在其上定义的一堆常量.但是它可以具有适合枚举数隐藏字段的任何整数值.
The reason I do this: this is the way it works in strongly-typed C#: an enum there is just a struct with a field of its underlying type, and a bunch of constants defined on it. But it can have any integer value that fits in the enum's hidden field.
似乎C ++枚举的工作方式完全相同.在这两种语言中,都必须将类型从枚举转换为int,反之亦然.但是,在C#中,按位运算符默认情况下会重载,而在C ++中则不会.
And it seems that C++ enums work in the exact same way. In both languages casts are required to go from enum to int or vice versa. However, in C# the bitwise operators are overloaded by default, and in C++ they aren't.
推荐答案
inline NumericType& operator |=(NumericType& a, NumericType b)
{
return a= a |b;
}
这行得通吗? 编译并运行:(Idone)
#include <iostream>
using namespace std;
enum class NumericType
{
None = 0,
PadWithZero = 0x01,
NegativeSign = 0x02,
PositiveSign = 0x04,
SpacePrefix = 0x08
};
inline NumericType operator |(NumericType a, NumericType b)
{
return static_cast<NumericType>(static_cast<int>(a) | static_cast<int>(b));
}
inline NumericType operator &(NumericType a, NumericType b)
{
return static_cast<NumericType>(static_cast<int>(a) & static_cast<int>(b));
}
inline NumericType& operator |=(NumericType& a, NumericType b)
{
return a= a |b;
}
int main() {
// your code goes here
NumericType a=NumericType::PadWithZero;
a|=NumericType::NegativeSign;
cout << static_cast<int>(a) ;
return 0;
}
打印3.
这篇关于如何在作用域枚举上重载| =运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!