3

I'm trying to create a Color class and some constants so I can use them like Color::Red in other parts of my code.

#ifndef COLOR_H
#define COLOR_H

#include <cstdint>

class Color
{
    uint8_t r;
    uint8_t g;
    uint8_t b;
    uint8_t a;

public:
    Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a);

    static constexpr Color Red = Color(255, 0, 0, 255);
};

#endif // COLOR_H

This code give the error:

Type Color is incomplete.

After toying around and doing a bit of researchs, the best I found would be to move Red out of the class, but then I lose the elegance of the Color:: qualifier.

Is there a better solution?

3
  • 1
    tldr of the dupe; Just define it as const inside the class and then use constexpr outside class. Commented Oct 11, 2024 at 2:00
  • The dupe is appropriate. However I editted and added relevant tags to make it easy to find for future searches. Commented Oct 11, 2024 at 6:27
  • Dupe perfectly answered my problem. Thanks for the tags, good idea. Commented Oct 11, 2024 at 9:34

1 Answer 1

2

You could define the constants in a namespace, like this:

namespace ColorConstants
{
    inline constexpr Color Red{255, 0, 0, 255};
    inline constexpr Color Green{0, 255, 0, 255};
    //...
}

Then you would get the qualification of ColorConstants::Red to use Red.

This also allows for using statements, in case you or someone else would like to make the code shorter instead of having to write an explict alias.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.