Can Objects Be Instantiated from Class Name Strings in C ?
Is there a mechanism in C to instantiate objects from strings representing their class names, eliminating the need for explicitly defining if-else statements for each potential derived class in a factory class?
Problem:
Consider the following class structure:
class Base; class DerivedA : public Base; class DerivedB : public Base; // etc...
And a corresponding factory class, BaseFactory, that creates instances of derived classes based on a specified class name string:
class BaseFactory { public: BaseFactory(std::string &sClassName) { msClassName = sClassName; }; Base * Create() { if(msClassName == "DerivedA") { return new DerivedA(); } else if(msClassName == "DerivedB") { return new DerivedB(); } // etc... }; private: string msClassName; };
However, this approach requires explicitly specifying each derived class within BaseFactory, which can become cumbersome as the number of derived classes grows.
Solution:
Unlike in languages like C#, C does not inherently provide a mechanism to dynamically create objects based on runtime type information. To achieve similar functionality, one can consider constructing a mapping between class names and object creation functions:
template<typename T> Base * createInstance() { return new T; } typedef std::map<std::string, Base*(*)()> map_type; map_type map; map["DerivedA"] = &createInstance<DerivedA>; map["DerivedB"] = &createInstance<DerivedB>;
Using this map, object instantiation becomes:
return map[some_string]();
Alternatively, one can register derived classes automatically during program initialization:
template<typename T> struct DerivedRegister : BaseFactory { DerivedRegister(std::string const& s) { getMap()->insert(std::make_pair(s, &createT<T>)); } }; // in derivedb.hpp class DerivedB { ...; private: static DerivedRegister<DerivedB> reg; }; // in derivedb.cpp: DerivedRegister<DerivedB> DerivedB::reg("DerivedB");
This approach eliminates the need for manual class registration, as it occurs automatically when the class is defined.
Summary:
Although C does not directly support object instantiation from class name strings, these techniques provide a way to achieve similar functionality by mapping class names to object creation functions or by automating the registration process.
The above is the detailed content of Can C Instantiate Objects from Class Name Strings?. For more information, please follow other related articles on the PHP Chinese website!