I'm having trouble deciding whether not this code should compile or if just both compilers I tried have a bug (GCC 4.2 and Sun Studio 12). In general, if you have a static class member you declare in a header file you are required to define it in some source file. However, an exception is made in the standard for static const integrals. For example, this is allowed:
#include <iostream>
struct A {
static const int x = 42;
};
With no need to add a definition of x outside the class body somewhere. I'm trying to do the same thing, but I also take the address of x and pass it to a template. This results in a linker error complaining about a lack of definition. The below example doesn't link (missing a definition for A::x) even when it's all in the same source file:
#include <iostream>
template<const int* y>
struct B {
static void foo() { std::cout << "y: " << y << std::endl; }
};
struct A {
static const int x = 42;
typedef B<&x> fooness;
};
int main()
{
std::cout << A::x << std::endl;
A::fooness::foo();
}
Which is bizarre since it works as long as I don't pass the address to a template. Is this a bug or somehow technically standards compliant?
Edit: I should point out that &A::x is not a runtime value. Memory is set aside for statically allocated variables at compile time.