Class can't have constants of own type inside?

Viewed 138

What I mean, is it possible to somehow do something like this?

class Color {
public:
    static constexpr Color BLACK = {0, 0, 0};

    constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {}

private:
    int r_;
    int g_;
    int b_;
};

Compilers complain about class Color being incomplete when defining BLACK constant.

2 Answers

You might move definition outside:

class Color {
public:
    static const Color BLACK;

    constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {}

private:
    int r_;
    int g_;
    int b_;
};
constexpr Color Color::BLACK = {0, 0, 0};

Demo

Alternatively, you can change the static variable to a function call:

class Color {
public:
    static constexpr Color BLACK() { return {0, 0, 0}; }

    constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {}

private:
    int r_;
    int g_;
    int b_;
};
Related