Liste von verschiedenen Class Typen?
-
wie kann man eine Liste von verschieden Class Typen (anstatt Objekten) in C++11 erstellen? Mein Ziel:
class ITyp {}; class TypA: public ITyp {}; class TypB: public ITyp {}; class TypC: public ITyp {}; container TypListe { TypA, TypB, TypC }; auto mytype = std::make_shared<ITyp>(TypListe.at(Eingabe));
-
Das könnte man z.B. auf diese Weise bewekstelligen:
#include <iostream> #include <map> #include <memory> #include <string> #include <functional> #include <type_traits> class ITyp { public: virtual ~ITyp() = default; virtual void hello() const = 0; }; class TypA: public ITyp { public: void hello() const override { std::cout << "Hello from TypA" << std::endl; } }; class TypB: public ITyp { public: void hello() const override { std::cout << "Hello from TypB" << std::endl; } }; class TypC: public ITyp { public: void hello() const override { std::cout << "Hello from TypC" << std::endl; } }; std::map<std::string, std::function<std::shared_ptr<ITyp>()>> types; template <typename T> void register_type(std::string name) { static_assert(std::is_base_of<ITyp, T>::value, "register_type: T must be derived from ITyp."); types.emplace(name, [](){ return std::make_shared<T>(); }); } std::shared_ptr<ITyp> create(std::string name) { auto iter = types.find(name); if (iter != std::cend(types)) return iter->second(); throw std::runtime_error("Unknown type."); } int main() { register_type<TypA>("TypA"); register_type<TypB>("TypB"); register_type<TypC>("TypC"); create("TypA")->hello(); create("TypB")->hello(); create("TypC")->hello(); return 0; }
Gruss,
Finnegan
-
Klasse!