Instead of saving the type in a map (which is not possible because types aren't first class objects in C++) you could store a deleter function in a map. Your factory function then becomes:
void* CreateA()
{
A *a = new A();
PointerDeleters[a] = [](void *obj) { delete static_cast<A*>(obj); };
return a;
}
or with a function template:
template<typename T>
void* Create() // maybe you want to forward c'tor args using variadic template
{
T *a = new T();
PointerDeleters[t] = [](void *obj) { delete static_cast<T*>(obj); };
return t;
}
And then invoke it to trigger the deletion of the object p
with unknown type:
void DeleteThing(void* p)
{
PointerDeleters[p]();
}
The map PointerDeleters
should then have the value type std::function<void(void*)>
.
A better solution would be (if your design allows it) to use a base class with a virtual destructor; then you can simply delete a pointer to that class without storing any additional information:
template<typename T>
BaseClass* Create()
{
return new T();
}
void DeleteThing(BaseClass* p)
{
delete p;
}