2

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' macro was used incorrectly)

I get the same error using __builtin_offsetof. Any ideas?

Thanks

Mat
  • 202,337
  • 40
  • 393
  • 406
impulsionaudio
  • 219
  • 2
  • 7

2 Answers2

1

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

Stan Prokop
  • 5,579
  • 3
  • 25
  • 29
1

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 ) ; 
hasvn
  • 1,054
  • 1
  • 11
  • 15