The X: I have a collection of unrelated container-like objects (vector, maps, trees,...) handling objects of different unrelated types. The lifetime of the objects in these containers is shared between some subsets of them. I have an object in charge of their synchronization. The simplest implementation of a synchronization class that I can think of would be to have a vector of BaseContainerLike
pointers, where BaseContainerLike
would be a class implementing a common interface for all of the container-like objects that I want to manage. But not all of them are container like. They could be used as container like, but making them inherit from a common base class feels very weird and I'm scared that it will couple my design very strongly.
So I've created a ContainerLikeInterface
class like this:
struct ContainerLikeInterface {
template<T>
ContainerLikeInterface(T& t)
: create([](int i){ return t->create(i); }), // this is just an example
delete([](int i){ return t->delete(i); }) {}
std::function<void(int)> create;
std::function<void(int)> delete;
};
template<class T>
ContainerLikeInterface make_containerLikeInterface(T& t) {
return ContainerLikeInterface(t);
}
This allows me to trivially create a vector of interfaces in a non-intrusive way (I can just partially specialize the constructor for different types). My code using this approach is slightly faster than when using inheritance, but it requires slightly more memory and longer compile times (but I don't prioritize compile times). I don't know however if this approach will scale well with my project. And I've read some articles about value-semantics in which people prefer to transfer the object ownership to the interface, so I have the following questions:
- What are the pros/cons of this approach?
- Is this going to give me some problems in the long term?
- Should I use inheritance instead?
- Should I implement this in a different way?
- Should I use a library instead? (boost::TypeErasure, adobe::poly, or pyrtsa/poly)