Search code examples
c++c++11bitset

Why auto deduces a reference object instead of bool for std::bitset::operator []


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.


Solution

  • 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];