Search code examples
c++namespaceslinkage

Wrapping message constants in namespace


I have a series of constant strings that correspond to message IDs; I'm trying to create a centralized place for these constants as they are used in various classes in my application. I was originally going to create a namespace containing them:

// MessageIDs.hh
namespace MessageIDs {
  const std::string kMessage1("Message1");
  ...
}

Then I started to read about internal/external linkage definitions and now I have a couple of questions.

1) Is the only disadvantage of not making the constants extern the fact that I wouldn't be able to use them as template arguments since they would have internal linkage?

2) Is there any other downside to my approach I am unaware of?


Solution

  • 1) I see one definite advantage of this approach: you always see the value of the defined constant in the right place. I.e. should the constants be defined extern, you would have to place the definitions in one cpp-file along with the initializers, and leave the header with extern const without the value, which would mislead the supporters a bit.

    The downside you mentioned (unability to use them as a template parameter), is really a minor one, do you often need a std::string template parameter? I haven't seen those thankfully.

    2) Maybe another minor one is that you have duplicate std::string objects actually in every translation unit including the header file, one can think of it as a downside.

    In this particular case of string constants it looks like const char* is the all-cases-best solution.