Consider the following code:
class Base {
virtual bool someFunc() = 0;
virtual ~Base() = default;
};
class Derived1 : public Base {
bool someFunc() override { ... }
};
class Derived2 : public Base {
bool someFunc() override { ... }
};
class MyClass {
public:
MyClass(std::vector<Base> derivedClasses) {
for (const auto dClass : derivedClasses) {
m_derivedClasses.emplace_back(std::make_shared<???>(dClass));
}
}
std::vector<std::shared_ptr<Base>> m_derivedClasses;
};
int main() {
std::vector<Base> listOfDerivedClasses = {Derived1(), Derived2()};
MyClass mClass(listOfDerivedClasses)
for (const auto dClass : m_derivedClasses) {
dClass.someFunc();
}
}
Essentially, I have a class that is given a list of derived classes in its constructor, and I want to convert it to a list of pointers to those derived classes so that I can execute the appropriate someFunc()
function in main()
. I can't seem to figure out how to get this working, do I need some template magic?
EDIT:
I could make the MyClass
constructor take a std::vector<Base*>
and likely get things to work like that, but it requires the consumer to create the pointers themselves and I'm hoping to shield them from that. In another class I worked on, where I wanted polymorphic behavior, I was able to achieve something like this using templates:
template <typename derivedTypeT, std::enable_if_t<std::is_base_of_v<Base, derivedTypeT>, bool> = true>
MyOtherClass(const derivedTypeT &dClass) : m_dClass(std::make_shared<derivedTypeT>(dClass)) {}
I don't know how I can make this work if the input is a std::vector
though, since it obviously could have multiple derived types. Is this something I could do with variadic templates?