简体   繁体   中英

static class constants vs namespace of constants

Imagine you want to instanciate "special" cases with a common name of a class. Let's take as an example the class Color, defined below:

struct Color {
    float r, g, b;
    constexpr Color(float r, float g, float b) : r(r), g(g), b(b) {}
};

And imagine we want define in some organized way constants such as "RED", "BLUE", etc. I came across with this two ways of defining them:

1) As static constants inside the Color class, such as Color::RED , Color::GREEN

2) Inside a namespace named as the plural of the class:

namespace Colors{
    constexpr Color RED(1, 0, 0);
    /* ETC */
}

So they are accessed as Colors::RED Colors::BLUE ...

I find the second one easier to maintain, as it only needs one definition per element, whilst the first one needs two declarations, one inside and another outside the class. However I'm not sure of its correctness.

In short: I'm asking about whether if the second one is a correct way of doing it or if I should go with the first one or any other alternative. I'm not referring to if it compiles, it does. I'm talking about good design practices.

It's completely up to you.

Personally I don't want to have to change the class definition whenever I add a new "preset". So, unless the class's implementation itself needs those constants, I'd keep them out of it.

However, you can't pass namespaces as template arguments so sometimes (in much more complicated scenarios) you're "stuck" with a class. Still, that doesn't have to be the class Color .


the first one needs two declarations, one inside and another outside the class

As of C++17, that's no longer true; we have inline .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM