开发者

g++ won't let me pass a template parameter to offsetof

开发者 https://www.devze.com 2023-02-17 17:25 出处:网络
When using g++ I pass a template parameter as the member variable to offsetof, and I get the following warning:

When using g++ I pass a template parameter as the member variable to offsetof, and I get the following warning:

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

Here is what my usage looks like:

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' 开发者_如何学Gomacro was used incorrectly)

I get the same error using __builtin_offsetof. Any ideas?

Thanks


Member data must be public, so use public or struct

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

Note that preprocessor alway try to split arguments at a comma, so use a typedef as a workaround.

#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;
}


edit: sorry, I misunderstood your question, so I have changed the answer + lt & gt


Had the same problem here, offsetof doesn't work with templated classes.

As a quick hack to solve this, just create a dummy object of that type, and calculate the offset by subtracting adresses:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号