I have a class whose static const members have the same type as the class. I am getting an error that class isn’t yet complete.
#include<iostream>
class Color
{
public:
Color(unsigned char _red, unsigned char _green, unsigned char _blue)
: red(_red), green(_green), blue(_blue)
{
}
Color(){}
unsigned char red, green, blue;
static const inline Color White{255, 255, 255};
};
int main()
{
std::cout << Color::White.red;
}
Either I can make them non-const but then it is error prone as then it can be changed. If I make them const then they must be defined where the declaration is.
I guess for this situation there is a need of static constructor.
>Solution :
For more complicated use cases, you can use a "factory" static method. This has the added benefit of making it possible to use White in constant expressions:
#include <iostream>
class Color
{
public:
unsigned char red, green, blue;
constexpr Color(unsigned char _red, unsigned char _green, unsigned char _blue)
: red(_red), green(_green), blue(_blue) {}
constexpr static Color White() {
return {255, 255, 255};
};
};
int main()
{
constexpr auto red_value = Color::White().red;
std::cout << static_cast<int>(red_value) << '\n';
}