I have the following situation:
basestuff
is a shared library that implements my base model...
derivedstuff
is different for every implementation and represent the application objects.
utilitystuff
is a shared library with utility functions.
Here is the code:
namespace basestuff {
class Base {} // Base model
virtual std::unique_ptr<Base> createNew(); // Factory
}
namespace derivedstuff {
class Derived : public Base {} // Derived model
// Factory implementation
std::unique_ptr<basestuff::Base> createNew () {
return str::unique_ptr<basestuff::Base>(new Derived);
}
}
namespace utilitystuff {
class Utility {
/// get data and populate the vector element
getDataList(std::vector<std::unique_ptr<basestuff::Base>> &list,
std::function<std::unique_ptr<basestuff::Base>()> &factory)
{
for (...)
{
// ... Read data from somewhere and populate it...
// create new element and add to vector
std::unique_ptr<basestuff::Base> item = factory();
list.push_back(std::move(item));
}
};
}
}
Here is the code I would like to have:
main()
{
utilitystuff::Utility reader;
derivedstuff::Derived dummy;
std::vector<std::unique_ptr<derivedstuff::Derived> myClassList;
reader.getDataList(&myClassList, dummy.createNew);
}
But this is not working, as unique_ptr
needs to be from Base
type and, even if I change it to Base
, getDataList()
does not accept the parameters as it differs from the Base
class.
Is there a way to make use only of Derived
on main()
and make Base
transparent to this level without the need to keep casting between one and another type ?
I´ve read the post here that is about casting, but I don´t wanna use casts here. I just wanna use the Derived
in the above layer and let the underlying layer (Base
) solve the problem.