Question about unions, since I rarely use them.
I am using a union to represent rgb pixel data, so it can be accessed as a continual array of uint8_t
or as individual rgb elements. (I think this is probably one of the few uses for unions.)
Something like this:
union PixelRGB
{
uint8_t array[3];
struct rgb
{
uint8_t b;
uint8_t g;
uint8_t r;
};
};
I've realized it would be nice to be able to apply operations like "and" and "or" on my pixel data. I'd like to do something like
PixelRGB::operator&=(const PixelRGB other)
{
this->rgb.r = other.r;
this->rgb.g = other.g;
this->rgb.b = other.b;
}
I tried putting an operator like this in the union but as far as I'm aware that's not allowed in C++. (I also got a compiler error when compiling - so from this I assume it is not allowed.)
One possible solution I've considered is wrapping the union in a class and then adding operators to that class. This is somewhat unpleasant with namespace/name-scope however.
Are there any other solutions?