2011-03-17 24 views
2

當使用G ++我通過一個模板參數作爲成員變量offsetof,我得到以下警告:克++不會讓我通過一個模板參數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得到相同的錯誤。有任何想法嗎?

感謝

回答

1

會員數據必須是公開的,所以使用公共或結構

 
template <typename T> 
class SomeClass { 
public: 
    T t; 
}; 
... 
offsetof(SomeClass<double>, t); 

注意,預處理器送花兒給人嘗試逗號分割的參數,所以使用typedef作爲一種解決方法。

 
#include <cstddef> 

template <typename T1, typename T2> 
class SomeClass { 
public: 
    T1 t1; 
    T2 t2; 
}; 

int main(int,char**) { 
    typedef SomeClass<double, float> SomeClassDoubleFloat; 
    offsetof(SomeClassDoubleFloat, t2); 

    return 0; 
} 


編輯:對不起,我誤解你的問題,所以我已經改變了答案+ LT & GT

1

有同樣的問題在這裏,offsetof不與模板類的工作。

作爲一個快速黑客解決這個問題,只需創建該類型的虛擬對象,並減去不會忽略計算偏移:

SomeClass<int> dummy ; 
const size_t offset = ((char*)(&dummy.t)) - ((char*) &dummy) ;