Home > Blockchain >  C class as namespace for static values
C class as namespace for static values

Time:03-14

Is there anyway to have the same API from namespace with a class

Exemple for namespace :

namespace Direction
{
    static const vec3 up = vec3(0, 1, 0);
}

// in code
{
   vec3 v = Direction::up;
}

whereas using a class I have to use a method

class Color : public vec4
{
    // class stuff //

    static Color black() {return Color(0, 0, 0, 1);}
}

// in code
{
   Color c = Color::black();
}

I want to be able to use Color c = Color::black; with Color being a class and black being defined in header. Is there any way to do it ?

EDIT : an other way to put it around is : Why does this gives me "incomplete type not allowed" and "a member of 'const Color' cannot have and in-class initializer"

class Color : public glm::vec4
{
public:
    explicit Color(const float r, const float g, const float b, const float a = 1.0f)
        : glm::vec4(r, g, b, a) {}

    static const Color a = Color(1, 1, 1, 0); // error
}

CodePudding user response:

try this

class Color 
{
    public:
    Color(int x, int y, int z, int t)
    {}
    const static Color BLACK;
};
const Color Color::BLACK{1,2,3,4};

int main()
{
   Color c = Color::BLACK;
}

I tested at https://godbolt.org/z/4oP55jTMK

  • Related