We have a rather large project that defines static const std::string
s 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
- There's a lot of these variables, i.e. a lot of code changes
- 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::string
s (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).