其他分享
首页 > 其他分享> > c – 在编译时比较静态字段指针

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

作者:互联网

我有一个派生自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));

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

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

解决方法:

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

这适用于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

标签:static-assert,c
来源: https://codeday.me/bug/20190901/1780766.html