0

I've been writing a simple class cFlags, which is meant for storing boolean flags in single variables, as opposed to creating multiple bools (all of which take one byte of memory). Everything is working well, but I've come across this problem while trying to simplify setting flag values. Skipping the irrelevant parts my code looks like this:

template <typename T>
cFlags
{
    public:
        bool get(char flag);
        void set(char flag, bool value);

    private:
        T flags_;
};

A created class holds a member variable of template type and allows to manage its bits with set() and get() methods (char arguments correspond to specific bits in the flags_ member).

Now, I came up with an idea that I should make an operator[] overload to make setting and getting flag values easier. The problem is, I couldn't find a way to make things like

cFlags<char> flags;
flags[0] = true;

possible, as the operator[] overload only returns an r-value bool that corresponds to whether a bit is lit or not. How should I go about implementing such functionality that I can do for example something like this:

cFlags<char> flags;
flags[0] = true;
if (flags[0]) {
    std::cout << "Bit 0 is active!";
}
Randoragon
  • 98
  • 1
  • 5
  • I'm not sure I understand what you're doing here, but perhaps instead of overloading the sub-script operator, you could just overload `operator=` instead, which you could have take a `bool` value, and you'd just write `flags = true` or whatever. – Tas Dec 15 '18 at 23:25
  • @Tas Maybe I didn't make it clear enough in thr l – Randoragon Dec 15 '18 at 23:27
  • @Tas Sorry, my finger slipped on the post button, i will reply properly now. The goal is to be able to access specific bits in a variable, so in my case "flags[0] = true" would mean that I'm taking the first bit of the member "flags_" and setting it to 1. – Randoragon Dec 15 '18 at 23:30
  • 1
    check how `vector`, bitset, etc are implemented? – Marc Glisse Dec 15 '18 at 23:57
  • 2
    Why not use `std::bitset`? – xskxzr Dec 16 '18 at 04:32

0 Answers0