简体   繁体   English

将地图结构转换为空指针和取消引用

[英]Cast map structure to void pointer and dereference

I have been trying to cast a map structure to a void pointer and cast it vice versa. 我一直在尝试将地图结构转换为空指针,反之亦然。

void addToMap(void *data){
// add some elements to the map
}

map<string, vector<myStruct> > myMap;
addToMap(&myMap);

I am trying to send myMap to addToMap function as an argument and add some elements inside the function. 我试图将myMap发送到addToMap函数作为参数,并在函数内部添加一些元素。 How can I deference the void parameter back to the map structure ? 我如何将void参数推回映射结构?

I know that static_cast can be used to dereference the void type to know types. 我知道static_cast可用于取消引用void类型以了解类型。 For instance: 例如:

int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);

The above snippet would work, but not in this case I suppose. 上面的代码片段可以工作,但我想在这种情况下不行。 I have already tried it out for my case, perhaps there has to be another trick. 我已经针对我的情况进行了尝试,也许还需要另一个技巧。

In addToMap function you can cast the void pointer back to the original type: 在addToMap函数中, 可以将void指针强制转换回原始类型:

void addToMap(void *data){
    auto pmap = static_cast<map<string, vector<myStruct> >*>(data);
    pmap->insert(...);
}

static_cast is also able to perform all conversions allowed implicitly (not only those with pointers to classes), and is also able to perform the opposite of these. static_cast还能够执行所有隐式允许的转换(不仅是那些指向类的指针),并且还可以执行相反的操作。 It can: 它可以:

Convert from void* to any pointer type. 从void *转换为任何指针类型。 In this case, it guarantees that if the void* value was obtained by converting from that same pointer type, the resulting pointer value is the same. 在这种情况下,它保证如果void *值是通过从相同的指针类型转换而获得的,则所得的指针值是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM