Search code examples
c++memberanonymous

C++ make member object unnamed


I want to write convinient Color management class, that would allow me to use different orders of components and basically different setups. I want it to be distinguishable at compile-time. Lets say I have this code:

template <typename _valueType>
struct RGBAColorData {
    using ValueType = _valueType;
    union {
        struct { ValueType r, g, b, a; };
        ValueType components[4];
    };
};

This (even if anonymous structs are non-standard) works fine, when I want to use it like this:

RGBAColorData color;
color.r = whatever;

However, this is not the final form of my code. I want it to have "owning" class template, that would in compile-time select between XYZColorData. Lets say it looks like this:

template <typename _valueType, template <typename> _dataScheme>
struct Color
{
    using ValueType = _valueType;
    using DataScheme = _dataScheme<ValueType>;

    // what now?
    // DataScheme data; // ???
};

This makes a problem, because I want my code to be used like this:

using RGBAColorF = Color<float, RGBAColorData>;
RGBAColorF brushColor;
brushColor.r = whatever;

This would make a really convinient way to use colors, however I can't think of any solution to this problem. Finally, maybe I have wrong approach to this and maybe this can be done with less effort, however I can't think about any other method that wouldn't involve massive amount of template class specializations.


Solution

  • Finally, I decided to use inheritance (as Ben Voigt said). I fixed the other problem, with unions that made code unsafe, using the brilliant method proposed by this answer:
    https://stackoverflow.com/a/494760/4386320