1

This is so wierd, i am coding a pixel manipulation library in C++. So i want to have a class filled with color presets. Color is a class with a struct that looks like:

Color(int r, int g, int b, int a) 

And if i declare it outside of any classes as:

static const Color COL_BLACK = Color(0, 0, 0, 255); 

That shows no error in Visual Studio Code. But however when i structure like this:

class Colors { public: static const Color Black = Color(0, 0, 0, 255); }; 

The equal sign has a red squiggly line under it, but when i hover my mouse over it doesn't tell me what is wrong. What is wrong?

Note that i want it to be called like so:

Color newCol = Colors::Black; 
3
  • Try static inline const Color Black = Color(0, 0, 0, 255); for the static member in Colors. ;-) Commented Nov 18, 2021 at 16:45
  • 1
    static members in a class declaration are a potential violation of the One Definition Rule (ODR) because the class declaration (in a header) could be repeated. In older standards, it was necessary to move the definition of static members into one translation unit (a .cpp file). Since recent standards (I believe C++17), an alternative option is the static inline (with the requirement that the static inlined hast to be equal at every time when its seen by the compiler again). Commented Nov 18, 2021 at 16:48
  • Though, a static definition of a global variable in a header is not that clever as well. Each time the header is seen, a new symbol will be generated... This symbol is exclusively visible in the corresponding object file but it still appears to be a waste (to me). Commented Nov 18, 2021 at 16:52

2 Answers 2

1

Since C++ 17 you can simply use inline like in the following:

#include <iostream> class Color { public: Color(int r, int g, int b, int a) : r{ r }, g{ g }, b{ b }, a{ a } { } int r, g, b, a; }; class Colors { public: inline static const Color Black = Color(0, 0, 0, 255); }; int main() { Color c = Colors::Black; std::cout << c.r << "," << c.g << "," << c.b << "," << c.a << "\n"; } 
Sign up to request clarification or add additional context in comments.

Comments

0

Read up a little on static initialization. In the meantime, in this case you could define Color with a constexpr ctor, like this:

struct Color { const unsigned int r; const unsigned int g; const unsigned int b; const unsigned int a; constexpr Color( const unsigned int r, const unsigned int g, const unsigned int b, const unsigned int a ) : r(r), g(g), b(b), a(a) {} }; 

And then you would initialize Colors like this:

class Colors { public: static constexpr Color Black = Color(0, 0, 0, 255); }; 

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.