将映射结构转换为无效指针并取消引用

Cast map structure to void pointer and dereference

我一直在尝试将映射结构转换为空指针,反之亦然。

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

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

我正在尝试将 myMap 作为参数发送到 addToMap 函数,并在该函数中添加一些元素。如何将 void 参数推回映射结构?

我知道 static_cast 可用于取消引用 void 类型以了解类型。例如:

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

上面的代码片段可以工作,但我想在这种情况下不行。我已经为我的情况尝试过了,也许必须有另一个技巧。

在 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. 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.