How to calculate offset of a class member at compile time?

Jun Yuan picture Jun Yuan · Nov 1, 2012 · Viewed 19k times · Source

Given a class definition in C++

class A
{
  public:
    //methods definition
    ....

  private:
    int i;
    char *str;
    ....
}

Is it possible to calculate the offset of a class member at compile time using C++ template meta-programming? The class is not POD, and can have virtual methods, primitive and object data member.

Answer

Glen Low picture Glen Low · Nov 22, 2013

Based on Matthieu M.'s answer but shorter and with no macros:

template<typename T, typename U> constexpr size_t offsetOf(U T::*member)
{
    return (char*)&((T*)nullptr->*member) - (char*)nullptr;
}

And it's called like this:

struct X { int a, b, c, d; }

std::cout << "offset of c in X == " << offsetOf(&X::c);

Edit:

Jason Rice is correct. This will not produce an actual constant expression in C++11. It doesn't look possible given the restrictions in http://en.cppreference.com/w/cpp/language/constant_expression -- in particular no pointer difference and reinterpret_castcan be in a constant expression.