문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top