workaround for pointers to bit fields (mimic std::bitset operator[])

I know in the C++ spec it states that pointers to bitfields are disallowed. There must be some sort of a workaround to this, however, as std::bitset seems to allow direct access (via pointer) to its bit fields (specifically with operator[]). How is this accomplished?

Is there any way to make something like the following work, such that you could manipulate the value of a bitfield with an external pointer (just like operator[] seems to do in std::bitset)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct Smybitfield
{
    unsigned int var1 : 8;
    unsigned int var2 : 8;
    unsigned int var3 : 8;
    unsigned int var4 : 4;
    unsigned int var5 : 2;
    unsigned int var6 : 1;
    unsigned int var7 : 1;
};

int main()
{
    Smybitfield mybitfield;
	
    mybitfield.var4 = 10u;
	
    char* char1ptr = static_cast<char*>(&mybitfield.var4); // char1ptr now points to var4 address, which has value 10

    *char1ptr = 11; // var4 now has value 11
}
Last edited on
std::bitset has overloaded operator[] to work that way and has nothing to do with pointers.
But can't you do the following with std:bitset? It has to return either a pointer or reference to an address for this to work!

1
2
3
4
5
6
int main()
{
    std::bitset<16> mybitset;

    mybitset[5] = 1; // operator[] has to return some callback to the memory address for this to work!
}

Last edited on
It's not a real reference that is returned. It's an instance of std::bitset::reference.
What's wrong with:

1
2
3
4
5
int main()
{
    std::bitset<16> mybitset;
    mybitset.set(5); 
}
Perhaps I could use std::bitset::reference in a similar way (or create my own). Nothing is wrong with using the bitset method set(), except I'm not trying to use bitset myself just mimic it's ability to have operator[] overloaded for what appear to be bitfields.

Is there any method you guys can think of to make the first example work, where *char1ptr can be used to reference a bitfield (ie. mybitfield.var4) of the same size?

Thanks for the help!
Last edited on
Topic archived. No new replies allowed.