Home >Backend Development >C++ >How Can I Instantiate C Objects from Class Name Strings?
Object Instantiation from Class Name Strings
In C , it's not possible to instantiate an object from a string containing the class name without explicit mapping. This limitation stems from the static nature of C , where types must be known at compile time.
Option 1: Manual Mapping Using Templates
You can create a template function for each class you want to instantiate and a map to link class names to the corresponding template functions. For example:
template<typename T> Base* createInstance() { return new T; } map_type map; map["DerivedA"] = &createInstance<DerivedA>; map["DerivedB"] = &createInstance<DerivedB>;
To instantiate an object, use:
return map[some_string]();
Option 2: Runtime Type Registration
You can have classes register themselves with a static mechanism and then retrieve instances dynamically. This involves using a singleton map to store class name to function mappings. Here's an example:
struct BaseFactory { static Base * createInstance(std::string const& s) { auto it = getMap()->find(s); return it != getMap()->end() ? it->second() : nullptr; } static std::map<std::string, std::function<Base*()>> * getMap() { if (!map) { map = new std::map<std::string, std::function<Base*()>>; } return map; } private: static std::map<std::string, std::function<Base*()>> * map; }; template<typename T> struct DerivedRegister : BaseFactory { DerivedRegister(std::string const& s) { getMap()->insert({s, &createInstance<T>}); } }; class DerivedB { private: static DerivedRegister<DerivedB> reg("DerivedB"); };
This method allows for automatic registration of classes at runtime.
Option 3: Boost Variant
If you have unrelated classes with no common base class, you can use the Boost variant library:
typedef boost::variant<Foo, Bar, Baz> variant_type; template<typename T> variant_type createInstance() { return variant_type(T()); } typedef std::map<std::string, variant_type (*)()> map_type;
This technique allows for instantiation of different types from a single string.
In conclusion, C lacks a built-in mechanism for object instantiation from class name strings. However, using templates, runtime registration, or the Boost variant library, you can achieve similar functionality.
The above is the detailed content of How Can I Instantiate C Objects from Class Name Strings?. For more information, please follow other related articles on the PHP Chinese website!