为什么析取赋值运算符 |= 不适用于布尔向量?
Why does the disjunction assignment operator |= not work with vectors of bools?
如果我有一个 vector<bool> vec_bool
,那么我不能使用 |=
赋值运算符修改向量的内容。也就是说,行
vec_bool[0] |= true;
vec_bool[0] |= vec_bool[1];
给出编译器错误,而行
bool a = false;
a |= true;
a |= vec_bool[0];
vec_bool[0] = vec_bool[0] | vec_bool[1];
vec_bool[0] = vec_bool[0] || vec_bool[1];
vector<int> vec_int(3);
vec_int[0] |= vec_int[1];
没有。这是什么原因?
gcc给出的错误是:
test.cpp:21:17: error: no match for ‘operator|=’ (operand types are ‘std::vector::reference {aka std::_Bit_reference}’ and ‘bool’)
从 std::vector<bool>
的 operator[]
返回的 reference
不是 bool&
的别名,因为它是 std::vector
的主要专业化。它是由 C++ standard as this:
指定的
// bit reference:
class reference {
friend class vector;
reference() noexcept;
public:
~reference();
operator bool() const noexcept;
reference& operator=(const bool x) noexcept;
reference& operator=(const reference& x) noexcept;
void flip() noexcept; // flips the bit
};
如您所见,没有声明 operator |=
。所以你不能将它应用到从 vec_bool[0]
.
返回的引用上
vec_bool[0] = vec_bool[0] | vec_bool[1];
起作用的原因是 上面有 重载来促进它。 operator bool()
将内置 |
的两个操作数转换为 bool
值。然后 reference
的赋值运算符将结果赋值回 vec_bool[0]
.
根据 C++ 标准的规定,std::vector<bool>
不是特别好的抽象,IMO。
如果我有一个 vector<bool> vec_bool
,那么我不能使用 |=
赋值运算符修改向量的内容。也就是说,行
vec_bool[0] |= true;
vec_bool[0] |= vec_bool[1];
给出编译器错误,而行
bool a = false;
a |= true;
a |= vec_bool[0];
vec_bool[0] = vec_bool[0] | vec_bool[1];
vec_bool[0] = vec_bool[0] || vec_bool[1];
vector<int> vec_int(3);
vec_int[0] |= vec_int[1];
没有。这是什么原因?
gcc给出的错误是:
test.cpp:21:17: error: no match for ‘operator|=’ (operand types are ‘std::vector::reference {aka std::_Bit_reference}’ and ‘bool’)
从 std::vector<bool>
的 operator[]
返回的 reference
不是 bool&
的别名,因为它是 std::vector
的主要专业化。它是由 C++ standard as this:
// bit reference:
class reference {
friend class vector;
reference() noexcept;
public:
~reference();
operator bool() const noexcept;
reference& operator=(const bool x) noexcept;
reference& operator=(const reference& x) noexcept;
void flip() noexcept; // flips the bit
};
如您所见,没有声明 operator |=
。所以你不能将它应用到从 vec_bool[0]
.
vec_bool[0] = vec_bool[0] | vec_bool[1];
起作用的原因是 上面有 重载来促进它。 operator bool()
将内置 |
的两个操作数转换为 bool
值。然后 reference
的赋值运算符将结果赋值回 vec_bool[0]
.
根据 C++ 标准的规定,std::vector<bool>
不是特别好的抽象,IMO。