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

前端 未结 4 1376
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 04:39

Given a class definition in C++

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

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

Is i

4条回答
  •  被撕碎了的回忆
    2020-12-09 05:14

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

    template 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.

提交回复
热议问题