There are several questions on Stack Overflow along the lines of "why can't I initialise static data members in-class in C++". Most answers quote from the standard telling you what you can do; those that attempt to answer why usually point to a link (now seemingly unavailable) [EDIT: actually it is available, see below] on Stroustrup's site where he states that allowing in-class initialisation of static members would violate the One Definition Rule (ODR).
However, these answers seem overly simplistic. The compiler is perfectly able to sort out ODR problems when it wants to. For example, consider the following in a C++ header:
struct SimpleExample
{
static const std::string str;
};
// This must appear in exactly one TU, not a header, or else violate the ODR
// const std::string SimpleExample::str = "String 1";
template <int I>
struct TemplateExample
{
static const std::string str;
};
// But this is fine in a header
template <int I>
const std::string TemplateExample<I>::str = "String 2";
If I instantiate TemplateExample<0>
in multiple translation units, compiler/linker magic kicks in and I get exactly one copy of TemplateExample<0>::str
in the final executable.
So my question is, given that it's obviously possible for the compiler to solve the ODR problem for static members of template classes, why can it not do this for non-template classes too?
EDIT: The Stroustrup FAQ response is available here. The relevant sentence is:
However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects
It seems however that those "complicated linker rules" do exist and are used in the template case, so why not in the simple case too?