简体   繁体   中英

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. How can I deference the void parameter back to the map structure ?

I know that static_cast can be used to dereference the void type to know types. 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:

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. It can:

Convert from void* to any pointer type. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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