3

クラス 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));

理論的にはこれらのアサーションはコンパイル時にチェックできますが、定数式はアドレスを取ることができないため、許可されません。

この種のチェックをコンパイル時に機能させる方法はありますか?

4

1 に答える 1

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
于 2013-03-21T00:24:51.940 に答える