I want a header file with a non-integral constant in it, e.g. a class. Note the constant does not need to be a compile-time constant.
static const std::string Ten = "10";
This compiles but is undesirable as each compilation unit now has its own copy of Ten.
const std::string Ten = "10";
This will compile but will fail with a linker error for multiply defined Ten.
constexpr std::string Ten = "10"s;
This would work but only if the strings constructor was constexpr as well. It will be but I can't count on every non-integral constant to have a constexpr constructor ... or can I?
extern const std::string Ten = "10";
This seems to work but I'm afraid I'll get a linker error if I breath on it wrong.
inline const std::string Ten( ) { return "10"; }
This has everything I want except a clean syntax. Plus now I have to refer the constant as a function call, Ten()
.
inline const std::string = "10";
This seems to be the ideal solution. Of course inline
variables aren't allowed by the standard.
- Is there something in the c++ standard that says the extern version should work or am I just lucky it works with GCC?
- Is there a compelling reason not to allow inline variables?
- Is there a better way with c++03 or will there be a better way in c++0x?