可変数のクラスのトップレベル クラスを作成するために使用される可変個引数クラス テンプレートがあります。最上位クラスに含まれる各クラスは、共通の機能があるため、基底クラスから派生します。派生クラスを親クラスに格納する最良の方法はわかりませんが、派生クラスのすべての機能にアクセスできます。
可変引数をベクトルに格納すると、それらはすべて基本クラスとして格納され、派生機能にアクセスできなくなります。それらをタプルに格納すると、派生型で関数にアクセスする方法がわかりません。SO で説明されているようにアクセスしようとすると、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
どうすればこれを達成できるかについて誰か提案がありますか?