在C ++中键入安全(R)位Flags?
-
26-09-2019 - |
题
在修改一些旧的C ++代码时,我遇到了几个 Bitflags 定义为枚举。
enum FooFlags
{
FooFlag1 = 1 << 0,
FooFlag2 = 1 << 1,
FooFlag3 = 1 << 2
// etc...
};
这并不少见,但是这让我感到困扰,一旦您开始结合标志,就会失去类型的信息。
int flags = FooFlag1 | FooFlag2; // We've lost the information that this is a set of flags relating to *Foo*
一种替代方法是将标志声明为#Defines或const积分,因此位操作不会转换类型(可能)。问题在于,它使我们的位设置为通过INT或其他枚举与无关的标志混合。
我很熟悉 std :: bitset 和 boost :: dynamic_bitset, ,但两者都不旨在解决我的问题。我正在寻找的是C# 标志性.
我的问题是,(更多)类型的安全集合集还有哪些其他解决方案?
我将在下面发布自己的解决方案。
解决方案 2
这是我自己的解决方案,使用当前版本的VS2010允许的C ++ 0x元素:
#include <iostream>
#include <numeric>
#include <string>
#include <initializer_list>
template <typename enumT>
class FlagSet
{
public:
typedef enumT enum_type;
typedef decltype(enumT()|enumT()) store_type;
// Default constructor (all 0s)
FlagSet() : FlagSet(store_type(0))
{
}
// Initializer list constructor
FlagSet(const std::initializer_list<enum_type>& initList)
{
// This line didn't work in the initializer list like I thought it would. It seems to dislike the use of the lambda. Forbidden, or a compiler bug?
flags_ = std::accumulate(initList.begin(), initList.end(), store_type(0), [](enum_type x, enum_type y) { return x | y; })
}
// Value constructor
explicit FlagSet(store_type value) : flags_(value)
{
}
// Explicit conversion operator
operator store_type() const
{
return flags_;
}
operator std::string() const
{
return to_string();
}
bool operator [] (enum_type flag) const
{
return test(flag);
}
std::string to_string() const
{
std::string str(size(), '0');
for(size_t x = 0; x < size(); ++x)
{
str[size()-x-1] = (flags_ & (1<<x) ? '1' : '0');
}
return str;
}
FlagSet& set()
{
flags_ = ~store_type(0);
return *this;
}
FlagSet& set(enum_type flag, bool val = true)
{
flags_ = (val ? (flags_|flag) : (flags_&~flag));
return *this;
}
FlagSet& reset()
{
flags_ = store_type(0);
return *this;
}
FlagSet& reset(enum_type flag)
{
flags_ &= ~flag;
return *this;
}
FlagSet& flip()
{
flags_ = ~flags_;
return *this;
}
FlagSet& flip(enum_type flag)
{
flags_ ^= flag;
return *this;
}
size_t count() const
{
// http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
store_type bits = flags_;
size_t total = 0;
for (; bits != 0; ++total)
{
bits &= bits - 1; // clear the least significant bit set
}
return total;
}
/*constexpr*/ size_t size() const // constexpr not supported in vs2010 yet
{
return sizeof(enum_type)*8;
}
bool test(enum_type flag) const
{
return (flags_ & flag) > 0;
}
bool any() const
{
return flags_ > 0;
}
bool none() const
{
return flags == 0;
}
private:
store_type flags_;
};
template<typename enumT>
FlagSet<enumT> operator & (const FlagSet<enumT>& lhs, const FlagSet<enumT>& rhs)
{
return FlagSet<enumT>(FlagSet<enumT>::store_type(lhs) & FlagSet<enumT>::store_type(rhs));
}
template<typename enumT>
FlagSet<enumT> operator | (const FlagSet<enumT>& lhs, const FlagSet<enumT>& rhs)
{
return FlagSet<enumT>(FlagSet<enumT>::store_type(lhs) | FlagSet<enumT>::store_type(rhs));
}
template<typename enumT>
FlagSet<enumT> operator ^ (const FlagSet<enumT>& lhs, const FlagSet<enumT>& rhs)
{
return FlagSet<enumT>(FlagSet<enumT>::store_type(lhs) ^ FlagSet<enumT>::store_type(rhs));
}
template <class charT, class traits, typename enumT>
std::basic_ostream<charT, traits> & operator << (std::basic_ostream<charT, traits>& os, const FlagSet<enumT>& flagSet)
{
return os << flagSet.to_string();
}
该界面是根据 std :: bitset. 。我的目的是忠于类型安全性和最低限度(如果有)的C ++精神。我欢迎对我的实施的任何反馈。
这是一个最小的例子:
#include <iostream>
enum KeyMod
{
Alt = 1 << 0, // 1
Shift = 1 << 1, // 2
Control = 1 << 2 // 4
};
void printState(const FlagSet<KeyMod>& keyMods)
{
std::cout << "Alt is " << (keyMods.test(Alt) ? "set" : "unset") << ".\n";
std::cout << "Shift is " << (keyMods.test(Shift) ? "set" : "unset") << ".\n";
std::cout << "Control is " << (keyMods.test(Control) ? "set" : "unset") << ".\n";
}
int main(int argc, char* argv[])
{
FlagSet<KeyMod> keyMods(Shift | Control);
printState(keyMods);
keyMods.set(Alt);
//keyMods.set(24); // error - an int is not a KeyMod value
keyMods.set(Shift);
keyMods.flip(Control);
printState(keyMods);
return 0;
}
其他提示
您可以超载操作员的枚举类型,以返回正确的键入结果。
inline FooFlags operator|(FooFlags a, FooFlags b) {
return static_cast<FooFlags>(+a | +b);
}
应该注意的是,在理论上是安全的,您应该手动声明最高的可能值,以确保枚举类型的范围可以捕获所有组合。
- 实际上不需要:枚举的范围将始终能够捕获所有组合,因为枚举范围的最高正值始终是
(2^N)-1
为了第一N
能够代表最高枚举者。该值具有所有位1。
以为我可能会添加C ++ 11版本 enum class
FooFlags operator|(FooFlags a, FooFlags b)
{
typedef std::underlying_type<FooFlags>::type enum_type;
return static_cast<FooFlags>(static_cast<enum_type>(a) | static_cast<enum_type>(b));
}
如果您的C ++ 11版本支持它,我想这将是 constexpr
不隶属于 StackOverflow