众所周知,C++中的内置枚举不是类型安全的.我想知道实现类型安全枚举的哪些类在那里使用...我自己使用以下"自行车",但它有点冗长和有限:
typesafeenum.h:
struct TypesafeEnum
{
// Construction:
public:
TypesafeEnum(): id (next_id++), name("") {}
TypesafeEnum(const std::string& n): id(next_id++), name(n) {}
// Operations:
public:
bool operator == (const TypesafeEnum& right) const;
bool operator != (const TypesafeEnum& right) const;
bool operator < (const TypesafeEnum& right) const;
std::string to_string() const { return name; }
// Implementation:
private:
static int next_id;
int id;
std::string name;
};
Run Code Online (Sandbox Code Playgroud)
typesafeenum.cpp:
int TypesafeEnum::next_id = 1;
bool TypesafeEnum::operator== (const TypesafeEnum& right) const
{ return id == right.id; }
bool TypesafeEnum::operator!= …Run Code Online (Sandbox Code Playgroud) 在什么情况下,使用bitset(STL容器)来管理一组标志而不是将它们声明为多个单独的(bool)变量更合适?
如果我使用50位标志的bitset而不是使用50个单独的bool变量,我会获得显着的性能提升吗?
我想为我当前的问题使用一组位标志.这些标志(很好地)被定义为一部分enum,但是据我所知,当你OR从枚举中获得两个值时,OR操作的返回类型具有类型int.
我目前正在寻找的是一种解决方案,它允许位掩码的用户保持类型安全,因此我创建了以下重载 operator |
enum ENUM
{
ONE = 0x01,
TWO = 0x02,
THREE = 0x04,
FOUR = 0x08,
FIVE = 0x10,
SIX = 0x20
};
ENUM operator | ( ENUM lhs, ENUM rhs )
{
// Cast to int first otherwise we'll just end up recursing
return static_cast< ENUM >( static_cast< int >( lhs ) | static_cast< int >( rhs ) );
}
void enumTest( ENUM v )
{
}
int …Run Code Online (Sandbox Code Playgroud)