C ++ - 11 for a map of heterogeneous objects

I have a cache of heterogeneous objects stored by name. Please note that there is no common base class for them. During creation, I also have to store the Deleter object (since I know the type at the time), so the map looks like this:

map<string, pair<void *, Deleter> > data; 

whenever an object is retrieved (using the template method), it returns back to the requested type. The cache destructor simply calls Deleter and removes the pair from the card. It all works.

It would be nice if C ++ 11 allowed me to do something like:

 map<string, unique_ptr_base> data; 

where unique_ptr_base will be the (imaginary) base class of all unique_ptr, and its virtual destructor will remove the element. Then I could just remove the item from the map and not worry about freeing it.

Writing a special class for this purpose is not too difficult, but in this case it is not justified, since this method takes only one more line, and there are not many dangers of pointer leakage. So, is there any feature of the new standard that I skip, or just leave it as it is?

+4
source share
1 answer

If you don't have stateful handlers, you can pretty much use:

 std::unique_ptr<void, void (*)(void *)> 

For instance:

 using any_ptr = std::unique_ptr<void, void (*)(void *)>; any_ptr p(static_cast<void *>(std::fopen("/dev/null")), [](void * x) { std::fclose(static_cast<FILE*>(x)); }); 
+4
source

Source: https://habr.com/ru/post/1490084/


All Articles