I have the following code
std::bitset<32> bs{21};
auto ref_obj = bs[0];
auto &another_ref = bs[0];
bool bool_obj = bs[0];
The type of ref_obj
is not bool
. But another_ref
has the same type as ref_obj
. std::bitset::operator[]
has 3 overloads listed at http://en.cppreference.com/w/cpp/utility/bitset/operator_at
But I could not figure out why it is so.
According to the C++11 standard, if your bitset is not const
(and yours isn't), then a reference type is returned:
§20.6.2 bitset operations:
constexpr bool operator[](size_t pos) const; // for b[i];
reference operator[](size_t pos); // for b[i];
The minimum addressable type in C++ is a byte which is presumably to be at least 8 bits [intro.memory/1] . Hence there is no way to return a reference to a single bit (which is less than 1 byte). So when you need a reference to that, a proxy that does some black magic is returned.
Your object isn't const
, hence it is assumed you may want to modify the element through the via the []
operator. You can cast it to a const
reference and access the const
qualified member overload.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.