tags:

views:

97

answers:

1

i'm using templated unions to both assure myself that i always get a 64-bit field for pointers (even on 32-bit machines since there is transmission of data to a 64-bit machine occurring) and to save both the user and myself casting.

template <typename type> union lrbPointer
{
    uint64_t intForm;
    type ptrForm; //assumed that type is a pointer type
};

//usage
lrbPointer<int*> myPointer;
int integers[4];
myPointer.ptrForm = integers;
myPointer.intForm += 2; //making it easy to jump by less then sizeof(int)

this is working well for me, but i would really love to find a way to make a default member. so that the user does not need to use a .ptrForm after the pointer they wish to use.

+4  A: 

You can use a conversion operator, along with a constructor, so you can transfer between the types:

template <typename PtrType>
union IntPointer
{
    uint64_t intForm;
    PtrType ptrForm;

    IntPointer(PtrType ptr) :
    ptrForm(ptr)
    {
    }

    operator PtrType(void) const
    {
        return ptrForm;
    }
};

int main(void)
{
    IntPointer<float*> f = new float; // constructor

    float *theFloat = f; // conversion operator

    delete theFloat;
}

That said, I think your treading on thin ground. :|

GMan
Disclaimer: I tried this without a compiler, let me know if something in there goes against the standard.
GMan
+1 Man, I didn't know you can have a conversion operator in a union :)
AraK
this looks like it should do the trick. and i like this better then another suggestion i got about using some sort of keyword to force a pointer out to 64 bytes even on a 32-bit machine (didn't fix the casting trouble).
Adam