C++ 枚举标志与位集
C++ enum flags vs bitset
枚举标志的 pros/cons 用法位集是什么?
namespace Flag {
enum State {
Read = 1 << 0,
Write = 1 << 1,
Binary = 1 << 2,
};
}
namespace Plain {
enum State {
Read,
Write,
Binary,
Count
};
}
int main()
{
{
unsigned int state = Flag::Read | Flag::Binary;
std::cout << state << std::endl;
state |= Flag::Write;
state &= ~(Flag::Read | Flag::Binary);
std::cout << state << std::endl;
} {
std::bitset<Plain::Count> state;
state.set(Plain::Read);
state.set(Plain::Binary);
std::cout << state.to_ulong() << std::endl;
state.flip();
std::cout << state.to_ulong() << std::endl;
}
return 0;
}
据我所知,bitsets 有更方便的 set/clear/flip 函数来处理,但枚举标志的使用是一种更广泛的方法。
bitsets 有哪些可能的缺点以及我应该在日常代码中使用什么以及何时使用?
你编译优化了吗?不太可能有24倍的速度系数。
对我来说,bitset 更胜一筹,因为它为您管理 space:
- 可以根据需要扩展。如果你有很多标志,你可能 运行 out of space in the
int
/long long
version.
- 可能需要更少的 space,如果你只使用几个标志(它可以适合
unsigned char
/unsigned short
- 我不确定实现是否应用了这个优化,虽然)
(广告模式开启)
您可以获得两者:方便的界面和最佳性能。还有类型安全。 https://github.com/oliora/bitmask
std::bitset 和 c 风格 enum
在管理标志方面都有重要的缺点。首先,让我们考虑以下示例代码:
namespace Flag {
enum State {
Read = 1 << 0,
Write = 1 << 1,
Binary = 1 << 2,
};
}
namespace Plain {
enum State {
Read,
Write,
Binary,
Count
};
}
void f(int);
void g(int);
void g(Flag::State);
void h(std::bitset<sizeof(Flag::State)>);
namespace system1 {
Flag::State getFlags();
}
namespace system2 {
Plain::State getFlags();
}
int main()
{
f(Flag::Read); // Flag::Read is implicitly converted to `int`, losing type safety
f(Plain::Read); // Plain::Read is also implicitly converted to `int`
auto state = Flag::Read | Flag::Write; // type is not `Flag::State` as one could expect, it is `int` instead
g(state); // This function calls the `int` overload rather than the `Flag::State` overload
auto system1State = system1::getFlags();
auto system2State = system2::getFlags();
if (system1State == system2State) {} // Compiles properly, but semantics are broken, `Flag::State`
std::bitset<sizeof(Flag::State)> flagSet; // Notice that the type of bitset only indicates the amount of bits, there's no type safety here either
std::bitset<sizeof(Plain::State)> plainSet;
// f(flagSet); bitset doesn't implicitly convert to `int`, so this wouldn't compile which is slightly better than c-style `enum`
flagSet.set(Flag::Read); // No type safety, which means that bitset
flagSet.reset(Plain::Read); // is willing to accept values from any enumeration
h(flagSet); // Both kinds of sets can be
h(plainSet); // passed to the same function
}
尽管您可能认为这些问题很容易在简单示例中发现,但它们最终会逐渐出现在每个在 c 风格 enum
和 std::bitset 之上构建标志的代码库中。
那么您可以做些什么来提高类型安全性呢?首先,C++11 的作用域枚举是对类型安全的改进。但这极大地阻碍了便利性。部分解决方案是对作用域枚举使用模板生成的按位运算符。这是一个很棒的博客 post,它解释了它是如何工作的,还提供了工作代码:https://www.justsoftwaresolutions.co.uk/cplusplus/using-enum-classes-as-bitfields.html
现在让我们看看这会是什么样子:
enum class FlagState {
Read = 1 << 0,
Write = 1 << 1,
Binary = 1 << 2,
};
template<>
struct enable_bitmask_operators<FlagState>{
static const bool enable=true;
};
enum class PlainState {
Read,
Write,
Binary,
Count
};
void f(int);
void g(int);
void g(FlagState);
FlagState h();
namespace system1 {
FlagState getFlags();
}
namespace system2 {
PlainState getFlags();
}
int main()
{
f(FlagState::Read); // Compile error, FlagState is not an `int`
f(PlainState::Read); // Compile error, PlainState is not an `int`
auto state = FlagState::Read | FlagState::Write; // type is `FlagState` as one could expect
g(state); // This function calls the `FlagState` overload
auto system1State = system1::getFlags();
auto system2State = system2::getFlags();
if (system1State == system2State) {} // Compile error, there is no `operator==(FlagState, PlainState)`
auto someFlag = h();
if (someFlag == FlagState::Read) {} // This compiles fine, but this is another type of recurring bug
}
这个例子的最后一行显示了一个在编译时仍然无法捕获的问题。在某些情况下,比较是否相等可能才是真正需要的。但大多数时候,真正的意思是 if ((someFlag & FlagState::Read) == FlagState::Read)
.
为了解决这个问题,我们必须区分枚举器的类型和位掩码的类型。这是一篇文章,详细介绍了我之前提到的部分解决方案的改进:https://dalzhim.github.io/2017/08/11/Improving-the-enum-class-bitmask/
免责声明:我是后面这篇文章的作者。
使用上一篇文章中模板生成的按位运算符时,您将获得我们在上一段代码中展示的所有好处,同时还会遇到 mask == enumerator
错误。
一些观察:
std::bitset< N >
支持任意位数(例如,超过 64 位),而底层整数类型的枚举被限制为 64 位;
std::bitset< N >
可以隐式地(取决于 std
实现)使用最小大小适合请求位数的基础整数类型,而需要显式声明枚举的基础整数类型(否则,int
将用作默认的基础整数类型);
std::bitset< N >
表示 N 位的通用序列,而 scoped 枚举提供可用于方法重载的类型安全;
- 如果
std::bitset< N >
用作位掩码,典型的 实现依赖于用于索引(!= 掩码)目的的附加枚举类型;
请注意,为了方便起见,可以将后两个观察结果组合起来定义一个强 std::bitset
类型:
typename< Enum E, std::size_t N >
class BitSet : public std::bitset< N >
{
...
[[nodiscard]]
constexpr bool operator[](E pos) const;
...
};
并且如果代码支持一些反射来获取显式枚举值的数量,则可以直接从枚举类型推导出位数。
- 作用域枚举类型没有按位运算符重载(可以使用 SFINAE 或所有作用域和非作用域枚举类型的概念轻松定义一次,但需要在使用前包含 ) 和 unsoped 枚举类型将衰减为基础整数类型;
- 枚举类型的按位运算符重载,需要比
std::bitset< N >
更少的样板(例如,auto flags = Depth | Stencil;
);
- 枚举类型同时支持有符号和无符号基础整数类型,而
std::bitset< N >
在内部使用无符号整数类型(移位运算符)。
FWIIW,在我自己的代码中,我主要使用 std::bitset
(和 eastl::bitvector
)作为 private
位/bool
容器用于 setting/getting 个位/ bool
秒。对于屏蔽操作,我更喜欢具有显式定义的基础类型和按位运算符重载的作用域枚举类型。
枚举标志的 pros/cons 用法位集是什么?
namespace Flag {
enum State {
Read = 1 << 0,
Write = 1 << 1,
Binary = 1 << 2,
};
}
namespace Plain {
enum State {
Read,
Write,
Binary,
Count
};
}
int main()
{
{
unsigned int state = Flag::Read | Flag::Binary;
std::cout << state << std::endl;
state |= Flag::Write;
state &= ~(Flag::Read | Flag::Binary);
std::cout << state << std::endl;
} {
std::bitset<Plain::Count> state;
state.set(Plain::Read);
state.set(Plain::Binary);
std::cout << state.to_ulong() << std::endl;
state.flip();
std::cout << state.to_ulong() << std::endl;
}
return 0;
}
据我所知,bitsets 有更方便的 set/clear/flip 函数来处理,但枚举标志的使用是一种更广泛的方法。
bitsets 有哪些可能的缺点以及我应该在日常代码中使用什么以及何时使用?
你编译优化了吗?不太可能有24倍的速度系数。
对我来说,bitset 更胜一筹,因为它为您管理 space:
- 可以根据需要扩展。如果你有很多标志,你可能 运行 out of space in the
int
/long long
version. - 可能需要更少的 space,如果你只使用几个标志(它可以适合
unsigned char
/unsigned short
- 我不确定实现是否应用了这个优化,虽然)
(广告模式开启) 您可以获得两者:方便的界面和最佳性能。还有类型安全。 https://github.com/oliora/bitmask
std::bitset 和 c 风格 enum
在管理标志方面都有重要的缺点。首先,让我们考虑以下示例代码:
namespace Flag {
enum State {
Read = 1 << 0,
Write = 1 << 1,
Binary = 1 << 2,
};
}
namespace Plain {
enum State {
Read,
Write,
Binary,
Count
};
}
void f(int);
void g(int);
void g(Flag::State);
void h(std::bitset<sizeof(Flag::State)>);
namespace system1 {
Flag::State getFlags();
}
namespace system2 {
Plain::State getFlags();
}
int main()
{
f(Flag::Read); // Flag::Read is implicitly converted to `int`, losing type safety
f(Plain::Read); // Plain::Read is also implicitly converted to `int`
auto state = Flag::Read | Flag::Write; // type is not `Flag::State` as one could expect, it is `int` instead
g(state); // This function calls the `int` overload rather than the `Flag::State` overload
auto system1State = system1::getFlags();
auto system2State = system2::getFlags();
if (system1State == system2State) {} // Compiles properly, but semantics are broken, `Flag::State`
std::bitset<sizeof(Flag::State)> flagSet; // Notice that the type of bitset only indicates the amount of bits, there's no type safety here either
std::bitset<sizeof(Plain::State)> plainSet;
// f(flagSet); bitset doesn't implicitly convert to `int`, so this wouldn't compile which is slightly better than c-style `enum`
flagSet.set(Flag::Read); // No type safety, which means that bitset
flagSet.reset(Plain::Read); // is willing to accept values from any enumeration
h(flagSet); // Both kinds of sets can be
h(plainSet); // passed to the same function
}
尽管您可能认为这些问题很容易在简单示例中发现,但它们最终会逐渐出现在每个在 c 风格 enum
和 std::bitset 之上构建标志的代码库中。
那么您可以做些什么来提高类型安全性呢?首先,C++11 的作用域枚举是对类型安全的改进。但这极大地阻碍了便利性。部分解决方案是对作用域枚举使用模板生成的按位运算符。这是一个很棒的博客 post,它解释了它是如何工作的,还提供了工作代码:https://www.justsoftwaresolutions.co.uk/cplusplus/using-enum-classes-as-bitfields.html
现在让我们看看这会是什么样子:
enum class FlagState {
Read = 1 << 0,
Write = 1 << 1,
Binary = 1 << 2,
};
template<>
struct enable_bitmask_operators<FlagState>{
static const bool enable=true;
};
enum class PlainState {
Read,
Write,
Binary,
Count
};
void f(int);
void g(int);
void g(FlagState);
FlagState h();
namespace system1 {
FlagState getFlags();
}
namespace system2 {
PlainState getFlags();
}
int main()
{
f(FlagState::Read); // Compile error, FlagState is not an `int`
f(PlainState::Read); // Compile error, PlainState is not an `int`
auto state = FlagState::Read | FlagState::Write; // type is `FlagState` as one could expect
g(state); // This function calls the `FlagState` overload
auto system1State = system1::getFlags();
auto system2State = system2::getFlags();
if (system1State == system2State) {} // Compile error, there is no `operator==(FlagState, PlainState)`
auto someFlag = h();
if (someFlag == FlagState::Read) {} // This compiles fine, but this is another type of recurring bug
}
这个例子的最后一行显示了一个在编译时仍然无法捕获的问题。在某些情况下,比较是否相等可能才是真正需要的。但大多数时候,真正的意思是 if ((someFlag & FlagState::Read) == FlagState::Read)
.
为了解决这个问题,我们必须区分枚举器的类型和位掩码的类型。这是一篇文章,详细介绍了我之前提到的部分解决方案的改进:https://dalzhim.github.io/2017/08/11/Improving-the-enum-class-bitmask/ 免责声明:我是后面这篇文章的作者。
使用上一篇文章中模板生成的按位运算符时,您将获得我们在上一段代码中展示的所有好处,同时还会遇到 mask == enumerator
错误。
一些观察:
std::bitset< N >
支持任意位数(例如,超过 64 位),而底层整数类型的枚举被限制为 64 位;std::bitset< N >
可以隐式地(取决于std
实现)使用最小大小适合请求位数的基础整数类型,而需要显式声明枚举的基础整数类型(否则,int
将用作默认的基础整数类型);std::bitset< N >
表示 N 位的通用序列,而 scoped 枚举提供可用于方法重载的类型安全;- 如果
std::bitset< N >
用作位掩码,典型的 实现依赖于用于索引(!= 掩码)目的的附加枚举类型;
请注意,为了方便起见,可以将后两个观察结果组合起来定义一个强 std::bitset
类型:
typename< Enum E, std::size_t N >
class BitSet : public std::bitset< N >
{
...
[[nodiscard]]
constexpr bool operator[](E pos) const;
...
};
并且如果代码支持一些反射来获取显式枚举值的数量,则可以直接从枚举类型推导出位数。
- 作用域枚举类型没有按位运算符重载(可以使用 SFINAE 或所有作用域和非作用域枚举类型的概念轻松定义一次,但需要在使用前包含 ) 和 unsoped 枚举类型将衰减为基础整数类型;
- 枚举类型的按位运算符重载,需要比
std::bitset< N >
更少的样板(例如,auto flags = Depth | Stencil;
); - 枚举类型同时支持有符号和无符号基础整数类型,而
std::bitset< N >
在内部使用无符号整数类型(移位运算符)。
FWIIW,在我自己的代码中,我主要使用 std::bitset
(和 eastl::bitvector
)作为 private
位/bool
容器用于 setting/getting 个位/ bool
秒。对于屏蔽操作,我更喜欢具有显式定义的基础类型和按位运算符重载的作用域枚举类型。