Question

I have a class B deriving from class A. A declares a static field f, and B might declare a similar field of the same name. The following does not work:

struct A { static int f; };
struct B : A { static int f; }; // A::f is different from B::f
struct C : A {}; // A::f is the same as C::f
BOOST_STATIC_ASSERT((&A::f != &B::f));
BOOST_STATIC_ASSERT((&A::f == &C::f));

Even though theoretically those assertions could be checked at compile time, they are disallowed since constant expressions cannot take addresses.

Is there a way to make this kind of check work at compile time?

Was it helpful?

Solution

Try putting the definitions of the static variables in scope of the static asserts.

This works fine with gcc 4.7.2:

struct A { static int f; };
struct B : A { static int f; };
struct C : A {};

int A::f;
int B::f;

static_assert(&A::f != &B::f, "B");
static_assert(&A::f == &C::f, "C");

int main()
{
}

Compile with:

$ g++ -std=gnu++11 test.cpp
$ ./a.out
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top