Setting the default join member

I use template joins to assure myself that I always get a 64-bit field for pointers (even on 32-bit machines, because data is being transferred to a 64-bit machine) and to save both the user and me.

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 works well for me, but I'd love to find a way to make the default member. so the user does not need to use .ptrForm after the pointer that they want to use.

+3
source share
1 answer

You can use the conversion operator together with the constructor so that you can pass between 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;
}

However, I think you are stepping on the thin earth .: |

+6
source

Source: https://habr.com/ru/post/1715286/


All Articles