C++ conversion: have pointer to object member, calculate pointer to object

141 views Asked by At

C++ has static_cast to convert base_class_pointer to derived_class_pointer.

It is very similar operation to convert object_data_member_pointer to object_pointer.

I wrote the function ConvertDataMemberPtrToObjectPtr using unsafe C type conversion.

  • How can this be done in a safe way? Link to the member must be specified as a template parameter member_ptr.
  • Whether there can be any problems if you use such an implementation?

Source:

#include <stdio.h>
#include <tchar.h>

template< class T, class Member_type, Member_type T::*member_ptr >
inline T *ConvertDataMemberPtrToObjectPtr(Member_type& member) {    
    //Got reference to member 'member' of object 'T', return pointer to object 'T'
    // obj_ptr = member_ptr - offset_of_member_field
    return (T*) ( ((char*)(&member)) - ( (char*) (  &( ((T*)(0))->*member_ptr ) )  ) );
}

struct Test {
    int a;
    int b;
};

int _tmain(int argc, _TCHAR* argv[]) {

    Test obj;

    printf("\n0x%08lX", ConvertDataMemberPtrToObjectPtr<Test,int,&Test::a>(obj.a));
    printf("\n0x%08lX", ConvertDataMemberPtrToObjectPtr<Test,int,&Test::b>(obj.b));

    // This is must be avoided when using ConvertDataMemberPtrToObjectPtr!!!
    printf("\n0x%08lX - error!", ConvertDataMemberPtrToObjectPtr<Test,int,&Test::a>(obj.b));

    return 0;
}

Using parents instead members and static_cast:

template <class T, int id=0>
class Link {
public:
    int value;
    T *GetObjectPtr() { return static_cast<T*>(this); }
};
enum MyLinkId { Main=0, Red=1 };
class MyItem : public Link<MyItem,Main>, public Link<MyItem,Red> {};

MyItem x;
Link<MyItem,Main> *p2 = &x;
Link<MyItem,Red> *p3 = &x;

printf("\n0x%08lX", p2->GetObjectPtr());
printf("\n0x%08lX", p3->GetObjectPtr());
1

There are 1 answers

2
AudioBubble On

What you are trying to achieve is impossible: The information to distinguish the members is missing. You would need a unique reference member which you could pass to your conversion function.

struct UniqueReferenceMember {};
struct Test {
    UniqueReferenceMember unique_reference_member;
    int a;
    int b;
};

Having that is pointless, though. There is the object pointer, which you can pass directly (maybe converted to void*);