c++templatesmethodsinterfacec++20

In C++, is there a way to provide object member name as template parameter?


I have multiple classes C1, C2, etc, each has different members variables, ex: C1M1, C1M2, C2N1, C2N2. And I have a pointer to data that could be an object of C1, C2 based on initial bytes. Is there a way to write a method/template method to which I can specify, pointer to data, C1 and M1. And I can write logic on how to interpret how to read the data.

template<class C, class C::Member>
Member* Access(void* ptr) {
    C* p = reinterpret_cast<C*>(ptr);
    return &p->Member;
}

Solution

  • The shown code code in the question is unclear. A working example

    template<class C, typename T, T C::*Member>
    auto* Access(void* ptr) {
        C* p = static_cast<C*>(ptr);
        return &p->*Member;
    }
    

    If T is known and fixed, for example int

    template<class C, int C::*Member>
    int* Access(void* ptr) {
        C* p = static_cast<C*>(ptr);
        return &p->*Member;
    }