I have a class Colour
:
class Colour {
public:
std::byte r;
std::byte g;
std::byte b;
std::byte a;
};
Now if I have a function
void foo(const Colour& c);
I want to be able to call it by passing a string that represents the colour:
foo("red"); // become (255, 0, 0, 255)
foo("#00ff00"); // become (0, 255, 0, 255)
foo("hsl(240, 100, 50)"); // become (0, 0, 255, 255)
And of course I don't want to parse the string everytime, I would like the compiler to parse it and replace the string by the colour.
The problem is that we constexpr constructors, it can't have a body and must directly initialize the r, g, b, a values, or I could have a private member colour
so I can initialize it like this:
class Colour {
public:
constexpr Colour(const std::string& str) : colour(parseString(str)) {}
private:
InternalColor colour; // contains the r, g, b, a
};
constexpr InternalColour parseString(const std::string& str) {
// ...
// Parse the string and return the colour
}
But I want to have access to the r, g, b, a values directly, not with an indirection, and I don't want member functions like r()
.
So how can I parse the colour string at compile time and replace it with the colour? And yes I could call myself a constexpr function that return the color, but the idea is to directly pass a string.
std::byte
for the RGBA values.std::uint8_t
is easier to deal with and describes the range perfectly.std::string
as parameter ofconstexpr
would require C++20...std::byte
, which was added in C++17, is defined asenum class byte : unsigned char {} ;
. You'll find that setting individual values becomes casting galore.