get Class from Pointer of member
    Ali Çehreli 
    acehreli at yahoo.com
       
    Thu May 24 09:41:17 PDT 2012
    
    
  
On 05/24/2012 05:29 AM, StefanvT wrote:
 > I have such a function in C++:
 >
 > template<class CB,class FIELD>
 > inline CB* get_class_from_field( FIELD CB::*field, FIELD* mp) {
 > return reinterpret_cast<CB*>(
 > reinterpret_cast<char*>(mp) -
 > reinterpret_cast<ptrdiff_t>(&(reinterpret_cast<CB*>(0)->*field)));
 > }
I think get_object_from_field() would be a better name.
 > Here I come with a pointer to a class member and can calculate the
 > pointer to the class, where the member is within. (Nothing spectacular
 > in c++)
 >
 > Is this also possible in D?
There are no pointers to members in D. In C++, member pointers carry the 
offset of the field. The same can be achieved by using the .offsetof 
property:
class C
{
     int i;
     int j;
}
CB get_object_from_field(CB, FIELD)(size_t offset, FIELD * f)
{
     return cast(CB)(cast(ubyte*)f - offset);
}
void main()
{
     auto c = new C;
     C c2 = get_object_from_field!C(c.j.offsetof, &c.j);
     assert(c2 is c);
}
I am pretty sure there are better solutions for a more specific problem.
Ali
-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
    
    
More information about the Digitalmars-d-learn
mailing list