在编译时比较静态字段指针

时间:2013-03-20 21:56:49

标签: c++ static-assert

我有一个从类A派生的B类.A声明一个静态字段f,B可能声明一个相同名称的类似字段。以下不起作用:

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));

尽管从理论上说这些断言可以在编译时检查,但是由于常量表达式不能占用地址,所以它们是不允许的。

有没有办法在编译时进行这种检查?

1 个答案:

答案 0 :(得分:5)

尝试将静态变量的定义放在静态断言的范围内。

这适用于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()
{
}

编译:

$ g++ -std=gnu++11 test.cpp
$ ./a.out
相关问题