Expose a private std::bitset field that is inside a class for modification

66 views Asked by At

I'm coding in a C++ project that hasn't advanced beyond C++11 yet.

Let's say I have an enum class as follows:

enum class Weekdays
{
    kSunday = 0,
    kMonday,
    ...
    kSaturday,
};

I want to create a class that has a private std::bitset field which keeps track of which weekdays are special. This class does lots of other things, too, so that I can't or shouldn't just use std::bitset<7u> directly. So I define:

class Foo
{
private:
    std::bitset<7u> _specialflags;
    
public:
    ... (*)
}

The way I want to use this class is as follows

void f()
{
   Foo obj;
    ...
   bool monday_is_special = obj[kMonday];
   // ... cue some calculations that show that Tuesday is just as
   // special as Monday is ...
   obj[kTuesday] = obj[kMonday];
}

So what do I have to insert at (*) to be able to use the class like that? In particular, I want to assign (!) to obj[kTuesday] and get the effect that inside obj, the field _specialflags[static_cast<size_t>(kTuesday)] is modified accordingly. So something like

inline bool operator[](Weekdays d) const { return _specialflags[static_cast<size_t>(d)]; }

doesn't cut it yet; it exposes the individual bits for reading but not for writing.

1

There are 1 answers

3
scohe001 On BEST ANSWER

The operator[] for bitset returns an std::bitset::reference. So if you have your function return that, you can modify the values in the bitset directly! For example:

enum class Weekdays
{
    kSunday = 0,
    ...,
    kSaturday,
    COUNT
};

class Foo {
    private:
        std::bitset<(ulong)Weekdays::COUNT> weekdayFlags;
    public:
        std::bitset<(ulong)Weekdays::COUNT>::reference operator[](Weekdays day) { 
            return weekdayFlags[(size_t)day];
        }
};

See it in action here: https://ideone.com/3yiG3C