Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static initialization order and concatenation of strings

We have a rather large project that defines static const std::strings in several places to be used as parameter names; some of them need to be concatenated during static initialization:

foo.h:

struct Foo {
  static const std::string ParamSuffix;
};

foo.cpp:

const std::string Foo::ParamSuffix = ".suffix";

bar.h:

struct Bar {
  static const std::string ParamPrefix;
};

bar.cpp:

const std::string Bar::ParamPrefix = "prefix";

baz.h:

struct Baz {
    static const std::string ParamName;
};

baz.cpp:

const std::string Baz::ParamName = Bar::ParamPrefix + Foo::ParamSuffix;

The problem is obviously the "static initialization fiasco" as it is undefined in which order the static const members are initialized.

I dislike the usual solution, i.e. replace all these variables by functions, because

  1. There's a lot of these variables, i.e. a lot of code changes
  2. The concatenations require special functions, which makes the code base inconsistent and even more ugly

I currently cannot use C++11, which would make things easier with its constexpr feature (I think).

The question is: Is there any trick that would allow me to concatenate static const std::strings (or wrapper objects or whatever) to initialize another static const std::string?

like image 470
arne Avatar asked Dec 03 '25 22:12

arne


1 Answers

The question is: Is there any trick that would allow me to concatenate static const std::strings (or wrapper objects or whatever) to initialize another static const std::string?

No trivial ones, other than the one you dislike: create functions for the static strings.

There are non-trivial alternatives though (e.g. replace all your hard-coded strings with a string container/string map and load the map on application start-up).

My recommendation though would be to go with static functions (the solution you rejected).

like image 188
utnapistim Avatar answered Dec 06 '25 12:12

utnapistim