我有一个可变参数类模板,用于为可变数量的类创建顶级类。顶层类中的每个类都派生自一个基类,因为它们有共同的功能。我不知道将派生类存储在父类中的最佳方式,但仍然能够访问派生类的全部功能。
如果我将可变参数存储在向量中,它们将全部存储为基类,我无法访问派生功能。如果我将它们存储在一个元组中,我无法弄清楚如何通过派生类型访问这些函数。如果我尝试按照此处讨论的方式访问它们,则 make_unique 不可用(C++14?)。
所以,我想做以下事情:
class BaseElement {
public:
virtual int polymorphicFunction() {return 0;};
};
class DerivedElement1 : public BaseElement {
public:
virtual int polymorphicFunction() {return 1;};
}
class DerivedElement2 : public BaseElement {
public:
virtual int polymorphicFunction() {return 2;};
}
template<typename... systems> // systems will always be of derived class of BaseElement
class System {
System() : subsystems(systems{}...) {} ; // all variadic elements stored in tuple
// tuple used below, the system elements don't need to be stored in a container, I just want to access them
// I'd be happy to use a vector or access them directly as a member variable
// provided that I can access the derived class. I can't use RTTI.
const std::tuple<systems...> subSystems;
// pointer or reference, I don't mind, but pd1/2 will always exist,
// (but perhaps be NULL), even if there is no derived element passed to the template parameter
DerivedElement1 *pd1;
DerivedElement2 *pd2;
};
//Desired usage
System<DerivedElement1> sys; // sys->pd1 == &derivedElement1WithinTuple, sys->pd2 == NULL
System<DerivedElement2> sys; // sys->pd2 == &derivedElement2WithinTuple, sys->pd2 == NULL
System<DerivedElement1, DerivedElement2> sys; // sys->pd1 == &derivedElement1WithinTuple, sys->pd1 == &derivedElement1WithinTuple
有人对我如何实现这一点有任何建议吗?