我使用std::bitset和枚举类来获得更方便的工具。但我在从operator[]返回值时遇到了编译错误:
error: non-const lvalue reference to type 'bool' cannot bind to a temporary of type 'std::__1::bitset<2>::reference' (aka '__bit_reference<std::__1::__bitset<1, 2> >')我必须通过引用返回它,才能给它赋值。下面是我的完整代码:
template<typename T>
struct EnumTraits;
template<typename T>
class EnumClassBitset
{
private:
std::bitset<static_cast<typename std::underlying_type<T>::type>(EnumTraits<T>::max)> m_bitset;
typename std::underlying_type<T>::type get_value(T v) const
{
return static_cast<typename std::underlying_type<T>::type>(v);
}
public:
bool& operator[](T pos)
{
return m_bitset[get_value(pos)];
}
bool test(T pos) const
{
return m_bitset.test(get_value(pos));
}
EnumClassBitset& reset(T pos)
{
m_bitset.reset(get_value(pos));
return *this;
}
EnumClassBitset& flip(T pos)
{
m_bitset.flip(get_value(pos));
return *this;
}
};
enum class BitFlags
{
Write,
Read,
NumOfFlags
};
template<>
struct EnumTraits<BitFlags>
{
static const BitFlags max = BitFlags::NumOfFlags;
};下面是我尝试使用它的方法:
EnumClassBitset<BitFlags> m_flags;
m_flags[BitFlags::Write] = true;
cout << "Write flag: " << m_flags[BitFlags::Write] << endl;感谢任何人的帮助,提前谢谢。
发布于 2020-11-03 19:45:04
std::bitset (和std::vector<bool>一样)不会从operator[]的非const-version返回operator[]。这是由技术原因造成的,因为bool变量只有一个字节大,而std::bitset的元素只有一个字节大。此外,bool as类型具有1字节的对齐要求,但std::bitset中的单个位是未对齐的。因此,普通的bool &不能引用这样的元素。
这就是std::bitset::operator[]返回std::bitset::reference类型的代理对象的原因。您可能必须转发此类型,而不是返回bool &。
https://stackoverflow.com/questions/64662134
复制相似问题