0

In the below example, I extract the class name from the template type T. Now I want to use this string to create an instance of a class. Is there a way to achieve it in C++?

template <typename T>
class factory
{
    T obj;
    std::string class_name;
public:
    factory(T obj)
    {
        this->obj = obj;

        class_name = boost::typeindex::type_id<T>().pretty_name();
        
        //some magic here
        class_name instance;
    }
};
coder
  • 123
  • 4
  • This sounds like an XY problem. Is there a reason why you cannot just call a suitable constructor directly using the type parameter T? – nanofarad Aug 20 '20 at 21:56
  • Nope, what's the problem you're trying to solve? – George Aug 20 '20 at 21:56
  • 2
    Duplicate? https://stackoverflow.com/questions/582331/is-there-a-way-to-instantiate-objects-from-a-string-holding-their-class-name https://stackoverflow.com/questions/33216932/create-new-object-by-string-that-repesent-class-name-in-c https://stackoverflow.com/questions/1096700/instantiate-class-from-name https://stackoverflow.com/questions/41188383/create-object-from-class-name-using-a-string-in-c https://stackoverflow.com/questions/6234295/dynamically-creating-an-instance-of-a-class-from-a-string-containing-the-class-n https://stackoverflow.com/questions/1096700/instantiate-class-from-name – Jerry Jeremiah Aug 20 '20 at 22:01
  • 1
    Does this answer your question? [Is there a way to instantiate objects from a string holding their class name?](https://stackoverflow.com/questions/582331/is-there-a-way-to-instantiate-objects-from-a-string-holding-their-class-name) – Jan Schultke Aug 20 '20 at 22:05

0 Answers0