2

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.

7
  • 2
    If you want the compiler to parse it, you'd be looking at user-defined literals.
    – MSalters
    Commented Mar 26, 2021 at 9:20
  • 2
    Unrelated: I wouldn't use std::byte for the RGBA values. std::uint8_t is easier to deal with and describes the range perfectly.
    – Ted Lyngmo
    Commented Mar 26, 2021 at 9:21
  • std::string as parameter of constexpr would require C++20...
    – Jarod42
    Commented Mar 26, 2021 at 9:31
  • @TedLyngmo Isn't a byte the same as uint8_t?
    – Voko
    Commented Mar 26, 2021 at 9:32
  • std::byte, which was added in C++17, is defined as enum class byte : unsigned char {} ;. You'll find that setting individual values becomes casting galore.
    – Ted Lyngmo
    Commented Mar 26, 2021 at 9:34

2 Answers 2

3

I don't want to parse the string everytime,

Even with a constexpr InternalColour parseString(const std::string_view& str)

None of the calls are in constant expressions, so apply at runtime (optimizer might help):

foo("red"); // become (255, 0, 0, 255)
foo("#00ff00"); // become (0, 255, 0, 255)
foo("hsl(240, 100, 50)"); // become (0, 0, 255, 255)

You would have to do:

constexpr Colour red{"red"}; // Parsed at compile time
foo(red);
// ...

with constexpr constructors, it can't have a body

C++11 rules are really strict. :/

Since C++14 rules have been relaxed a lot.

Even in C++11, you might use delegating constructor to by-pass that issue.

class Colour {
public:
  constexpr Colour(std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint8_t a) :
      r(r), g(g), b(b), a(a) {}
  // not `explicit`, as you want implicit conversion
  constexpr Colour(const std::string_view& str) : Colour(parseString(str)) {}

  constexpr Colour(const Colour& rhs) = default;
  constexpr Colour& operator= (const Colour& rhs) = default;

public:
    static constexpr Colour parseString(const std::string_view& str)
    {
        // constexpr parsing in C++11 might be non trivial,
        // but possible (one return statement only :/ )

        if (str == "red") { return {255, 0, 0, 255}; }
        // ...
    }

public:
    std::uint8_t r;
    std::uint8_t g;
    std::uint8_t b;
    std::uint8_t a;
};
3

If you are willing to define your own user-defined literals, you could get those to create constexpr Colour instances.

"[...] literal operators and literal operator templates are normal functions (and function templates), they can be declared inline or constexpr, they may have internal or external linkage, they can be called explicitly, their addresses can be taken, etc."

I also recommend using std::uint8_t for the RGBA values since it is a perfect match for the [0,255] range. A std::byte is "just a collection of bits".

C++14 example:

#include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>

namespace colours {
    struct Colour {
        std::uint8_t r;
        std::uint8_t g;
        std::uint8_t b;
        std::uint8_t a;
    };

    // helper to display values
    std::ostream& operator<<(std::ostream& os, const Colour& c) {
        std::ostringstream oss;
        oss << std::hex << std::setfill('0')         << '{'
            << std::setw(2) << static_cast<int>(c.r) << ',' 
            << std::setw(2) << static_cast<int>(c.g) << ','
            << std::setw(2) << static_cast<int>(c.b) << ','
            << std::setw(2) << static_cast<int>(c.a) << '}';
        return os << oss.str();
    }

    // decode a nibble
    constexpr std::uint8_t nibble(char n) {
        if(n >= '0' && n <= '9') return n - '0';
        return n - 'a' + 10;
    }

    // decode a byte
    constexpr std::uint8_t byte(const char* b) {
        return nibble(b[0]) << 4 | nibble(b[1]);
    }

    // User-defined literals - These don't care if you start with '#' or
    // if the strings have the correct length.

    constexpr int roff = 1; // offsets in C strings
    constexpr int goff = 3;
    constexpr int boff = 5;
    constexpr int aoff = 7;

    constexpr Colour operator ""_rgb(const char* s, std::size_t) {        
        return {byte(s+roff), byte(s+goff), byte(s+boff), 0xff};
    }

    constexpr Colour operator ""_rgba(const char* s, std::size_t) {
        return {byte(s+roff), byte(s+goff), byte(s+boff), byte(s+aoff)};
    }

    // constants
    constexpr auto red   = "#ff0000"_rgb;
    constexpr auto green = "#00ff00"_rgb;
    constexpr auto blue  = "#0000ff"_rgb;
}

void foo(const colours::Colour&) {

}

int main() {
    using namespace colours;

    constexpr Colour x = "#abcdef"_rgb;
    std::cout << x << '\n';

    std::cout << "#1122337f"_rgba << '\n';

    std::cout << red << green << blue << '\n';

    foo(red);                   // become (255, 0, 0, 255)
    foo("#00ff00"_rgb);         // become (0, 255, 0, 255)
    // foo("240,100,50"_hsl);   // I don't know hsl, but you get the picture
}

Output:

{ab,cd,ef,ff}
{11,22,33,7f}
{ff,00,00,ff}{00,ff,00,ff}{00,00,ff,ff}
2
  • 1
    BTW, UDL are "just" regular functions, with an possible alternative call syntax.
    – Jarod42
    Commented Mar 26, 2021 at 11:59
  • @Jarod42 Yes, that's good info. I added a note at the top.
    – Ted Lyngmo
    Commented Mar 26, 2021 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.