I was hoping C++11 would allow a clean way of defining constants that are scoped inside a class (to prevent pollution of or collisions in the global namespace). My attempt led me to this technique:
struct Foo {
static constexpr const char* BAZ = "BAZ";
}
However, this will sometimes result in linker failures about undefined references to BAR. Indeed, this is not a definition of BAR, but a definition of its default value. Right?
What confuses me is that this sometimes works. I'll take a guess as to why... constexpr tells the compiler that it can treat this as a compile time constant, but it doesn't have to. So in some cases where BAR is used, the compiler may treat it as a compile time constant (and the translation unit would have a pointer effectively to the .rodata section (or .text or whatever the case may be) of the binary), and in others it may reference the variable BAR (and expect it to be resolved by the linker.) Is this logic sound?
So my question: Is there a way to make this technique work, perhaps by coercing the compiler to prefer treating this as a compile time constant in all cases?
Note that a proper definition of BAR (e.g. Foo:BAR; in source file) is not a viable solution -- keeping up with two lines of code for a constant is cumbersome.