Home > OS >  How to get a lvalue reference to a bit in std::bitset
How to get a lvalue reference to a bit in std::bitset

Time:11-09

I was trying to do the following:

std::bitset<2000> a_bit_set{};
auto& a_bit = a_bit_set[5];
if (complicated_predicate(a_bit, other_params))
{
  a_bit.flip();
}

but clang complains:

non-const lvalue reference to type 'std::bitset<2000>::reference' cannot bind to a temporary of type 'std::bitset<2000>::reference'

I am suspecting this is because the operator[] is returning a rvalue rather than a lvalue here. But according to cppreference, there is a special class std::bitset<>::reference that should allow me to reference a particular bit in a bitset. My question is: Can I get a lvalue reference to a particular bit in a bitset (akastd::bitset<>::reference)?

CodePudding user response:

How to get a lvalue reference to a bit in std::bitset

You don't. std::bitset doesn't contain any objects that represent an individual bit, and thus you cannot have a reference to such object.

aka std::bitset<>::reference

std::bitset<>::reference isn't an lvalue reference. It is an object - a reference wrapper. The subscript operator returns that object as a prvalue. You can simply use a copy of that reference wrapper like this:

auto a_bit = a_bit_set[5];

Or you can use an rvalue reference which extends the lifetime of the prvalue:

auto&& a_bit = a_bit_set[5];

I wouldn't use the latter in this example since it introduces unnecessary complexity. But it can potentially be useful in some other cases that involve templates with a reference alias that may be either a true reference or a reference wrapper depending on template arguments.

  •  Tags:  
  • c
  • Related