2

g++ を使用しているときに、テンプレート パラメーターをメンバー変数として offsetof に渡すと、次の警告が表示されます。

invalid access to non-static data member 'SomeClass::t' of NULL object
(perhaps the 'offsetof' macro was used incorrectly)

私の使い方は次のとおりです。

template<typename T> class SomeClass { T t; };
...
offsetof(SomeClass, t); //warning: invalid access to non-static data member 'SomeClass::t' of NULL object, (perhaps the 'offsetof' macro was used incorrectly)

__builtin_offsetof を使用しても同じエラーが発生します。何か案は?

ありがとう

4

2 に答える 2

1

ここでも同じ問題があり、offsetof はテンプレート化されたクラスでは機能しません。

これを解決する簡単なハックとして、そのタイプのダミー オブジェクトを作成し、アドレスを減算してオフセットを計算します。

SomeClass<int> dummy ;
const size_t offset =  ( (char*)(&dummy.t) ) - ( (char*) &dummy ) ; 
于 2011-09-07T10:01:00.567 に答える