mardi 3 juillet 2018

Using static const structs to group related constants (C++11)

What are the (dis)advantages of using the following (A):

// .h
class SomeClass
{
    static const struct ConstantGroup
    {
        int a = 1;
        string b = "b";
        // ... etc.
    } CONSTANT;
};
// .cpp
const SomeClass::ConstantGroup SomeClass::CONSTANT;

Versus (B):

// .h
class SomeClass
{
    static const int A;
    static const string B;
    // .. etc.
};
// .cpp
const int SomeClass::A = 1;
const string SomeClass::B = "b";

...for some group(s) of related static class constants? Assume no templates are involved and that the constants contain simple types (POD or strings).

So far I see the following advantages in favor of (A):

  • Related constants can be passed around as a group.
  • Given that the constants are often accessed together, we can create shorthands for the structure to improve readability when needed, i.e.: static const auto & SHORTHAND = SomeClass::LONG_NAME_FOR_CONSTANTS;

What are the disadvantages, gotcha's, or other things to keep in mind when using this pattern?

Aucun commentaire:

Enregistrer un commentaire