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.
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_cast
can be in a constant expression.