Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ structured bindings not working with bitset

Tags:

c++

c++17

I was writing a function that needed to return multiple variables, one of them being a bitset. Then I encountered some strange compilation error.

I tried different compilers, they all produce an error, albeit with different messages.

I tried googling, it seems that it has something to do with public and private inheritance. But I don't think it should affect this piece of code in any way.

The simplified code (C++17) looks like this:

#include <bitset>
auto f() { return bitset<100>(); }

int main()
{
    auto [a] = f();
    return 0;
}

If I remove the square brackets (i.e. remove the structured binding and use normal auto), it works.

The error messange is as follows:

source.cpp: In function 'int main()':

source.cpp:9:18: error: 'std::_Base_bitset<2>' is an inaccessible base of 'std::bitset<100>'

9 |     auto [a] = f();

  |                  ^

Compiler returned: 1

So my question is: Is this expected behaviour or am I doing something wrong? Suggestions are welcome.

like image 713
FallingStar Avatar asked Mar 20 '26 14:03

FallingStar


1 Answers

There are three kinds of types that work with structured bindings:

  • language arrays
  • types that opt-in to the tuple protocol (i.e. they provide specializations of tuple_size and tuple_element and overloads of get)
  • types for which all of their members are public members of the same base class (~ish)

std::bitset is none of these. Its specification does not say what its members are, and it does not provide an opt-in to the tuple protocol. Hence, it does not work with structured bindings. It is expected that auto [a] = f(); would fail.

If anything, why would a bitset<100> only provide a single binding? I would expect that if it provided bindings, it would provide 100 of them...

like image 119
Barry Avatar answered Mar 22 '26 06:03

Barry