Imagine I have a C++ struct called Color
struct Color {
float r,g,b;
};
and a function that accepts a Color object and does something with it:
void func(const Color & color) {...}
Usually, I call this function with Color objects constructed on the fly:
func(Color{0.1,0.2,0.3});
But there are certain colors that I use a lot, for example, black, white and red. So I find myself doing this a lot:
func(Color{0.0,0.0,0.0}); // black
func(Color{1.0,1.0,1.0}); // white
func(Color{1.0,0.0,0.0}); // red
What I would like to do instead is
func(Color::black);
func(Color::white);
func(Color::red);
So I am looking for a way to define global constants of type Color inside the Color namespace. So far, I've tried these two options:
Option 1: define a namespace with the same name as the struct; doesn't work because of conflicting namespaces.
struct Color {
float r,g,b;
};
namespace Color {
const Color black{0.0,0.0,0.0};
const Color white{1.0,1.0,1.0};
const Color red{1.0,0.0,0.0};
}
Option 2: static variables inside of the struct definition; doesn't work since this makes the struct definition incomplete.
// static members
struct Color {
float r,g,b;
static Color red = Color{1.0,0.0,0.0};
};
Is there a way to achieve what I want, or at least something similar?