Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 设置默认的联合成员_C++ - Fatal编程技术网

C++ 设置默认的联合成员

C++ 设置默认的联合成员,c++,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]

我使用模板联合来确保我总是为指针获得一个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)
模板联合LRB指针
{
uint64_t intForm;
类型ptrForm;//假定该类型是指针类型
};
//用法
lrbPointer-myPointer;
整数[4];
myPointer.ptrForm=整数;
myPointer.intForm+=2//使跳转速度小于sizeof(int)变得容易

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

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

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;
}
模板
并集指针
{
uint64_t intForm;
ptr型ptrForm;
IntPointer(ptr类型ptr):
ptr表格(ptr)
{
}
运算符PtrType(void)const
{
返回ptrForm;
}
};
内部主(空)
{
IntPointer f=new float;//构造函数
float*theFloat=f;//转换运算符
删除该文件;
}

也就是说,我认为你是在原地踏步|

你不能这样做(默认的工会成员),我看不出这有什么帮助。如果在两台机器之间传输指针值,即使它们是相同的体系结构,该值在另一台机器上也不会有任何意义,因此听起来您的数据传输/存储策略有问题?我向接收机器询问它将在哪里启动数据块的内存地址,有了这些信息,我可以计算接收机器上的指针。当然,这会使发送机器上的所有内容都无法读取,但我的目标是在发送机器上做更多的工作,因为这两台机器上的处理器和环境非常不同。目前,这个问题只是让用户看不清代码的问题,我的功能正在发挥作用。免责声明:我在没有编译器的情况下尝试了这个方法,如果其中有违反标准的内容,请告诉我。+1人,我不知道你可以在一个联合体中使用转换运算符:)这看起来应该可以做到。我更喜欢这个,而我得到的另一个建议是使用某种关键字强制指针指向64字节,即使在32位机器上也是如此(没有解决强制转换的问题)。