..

enum class重载operator

背景

有个表示状态的结构,前端可以通过接口来进行设置,状态用 enum class 来表示。

结构如下

enum class TokenState {
    Normal = 0x00,   
	Frozen = 0x01,
	Non_Frozen = 0x02,
	Ex = 0x04,
};

添加 operator

为了方便对state的更新操作,如

currentState |= appendState;

给 TokenState 重载 operator。

inline TokenState operator |(TokenState a, TokenState b)
{
    return static_cast<TokenState>(static_cast<int>(a) | static_cast<int>(b));
}

inline TokenState operator &(TokenState a, TokenState b)
{
    return static_cast<TokenState>(static_cast<int>(a) & static_cast<int>(b));
}

inline TokenState& operator |= (TokenState& a, TokenState b)
{
    return a = a | b;
}

通过对 TokenState 重载 |&|= 即可满足上述要求。


Nothing