user62039
user62039

Reputation: 371

How to design a colour class that has already pre-defined standard colours in the most elegant c++ way?

How to design a Colour class that has already pre-defined the standard colours in the modern elegant c++ way? I would like to know a minimal example design that does so instead of a complete colour class.

I have the basic Colour class:

class Colour
{
    public:
    double rgb[3];
};

Now I can use it in the following way:

Colour c1 = {1.0, 0.0, 0.0}, c2 = {1.0, 1.0, 0.0};

But since there are already standard colours very common to us that we will always like to use something like the following:

Colour c1 = Colour::Red, c2 = Colour::Yellow;

How to achieve the above?

Advance thanks.

Upvotes: 4

Views: 295

Answers (2)

Empty Space
Empty Space

Reputation: 751

If you are willing to provide a converting constructor in Colour class then you can define standard colours to be arrays and then convert to Colour object at the time of construction.

#include <array>

struct Colour {
    Colour(std::array<double, 3> _rgb) : rgb(_rgb) {}

    std::array<double, 3> rgb;

    static constexpr auto Red = std::array<double, 3>{1.0, 0.0, 0.0};
    static constexpr auto Yellow = std::array<double, 3>{1.0, 1.0, 0.0};
};

Colour c1 = Colour::Red, c2 = Colour::Yellow;

Upvotes: 2

Evg
Evg

Reputation: 26292

With a slightly different syntax, you can use static member functions:

struct Colour {
    double rgb[3];

    static constexpr Colour Red() {
        return {1, 0, 0};
    }
};

auto red = Colour::Red();

Alternatively, you can put standard colours into a special namespace:

namespace Colours {
    inline constexpr auto Red = Colour{1, 0, 0};
}

auto red = Colours::Red;

Upvotes: 4

Related Questions