Bencri
Bencri

Reputation: 1283

Static constexpr within its own class

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?

Upvotes: 3

Views: 95

Answers (1)

NathanOliver
NathanOliver

Reputation: 180660

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.

Upvotes: 2

Related Questions