设置默认联合成员

时间:2009-08-16 22:06:22

标签: c++

我正在使用模板化的工会,以确保自己总是得到一个64位字段的指针(即使在32位机器上,因为有数据传输到64位机器)并且保存两者用户和我自己铸造。

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)

这对我来说效果很好,但我真的很想找到一种制作默认会员的方法。这样用户就不需要在他们希望使用的指针之后使用.ptrForm。

1 个答案:

答案 0 :(得分:6)

您可以使用转换运算符和构造函数,以便在类型之间进行转换:

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;
}

那就是说,我认为你的踩踏了。 :|