1

Possible Duplicate:
minimal reflection in C++

Basically I have class name stored in char * , how Do i create instance of that class. Following is what I was thinking. It works when I pass Test as template parameter which is fine, but if I try something like this Test *t = CreateType<ptr> it will not work.

Is there any way to make this work.

class Test{
public:
    Test() {
    }
    ~Test() {
    }
};

template <typename T> 
T* CreateType() {
    return new T;
}

int main ( int argc, char **argv) {
    char *ptr = "Test";
    Test *T = CreateType<Test>();
    return 0;
}
Community
  • 1
  • 1
Avinash
  • 12,851
  • 32
  • 116
  • 186

2 Answers2

5

It is not directly possible in C++, because the language is not introspective.

You can try to do something similar though. For example, you can have a map< string, baseClassPointer > where the key will be the class' name, and the value will be a pointer to that class' object. Then you can create other objects by copying an object from the map (which you can get by the type name). I wouldn't suggest doing things like that though.

Factory pattern may suit your needs though.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
4

This is not possible in C++, since there is no mechanism like reflection in C++. What you can do is to write a factory, that knows how to construct an object from a string.

class Base
{
public:
    virtual ~Base(){}
};

class Factory
{
public:
    typedef std::function<Base*()> Creator;

    void Register(const std::string& key, Creator creator)
    {
        creators_[key] = creator;
    }

    std::unique_ptr<Base> Create(const std::string& key)
    {
        auto creator = creators_[key];
        auto instance = std::unique_ptr<Base>(creator());
        return instance;
    }

private:
    std::unordered_map<std::string, Creator> creators_;
};


class Concrete : public Base
{

};


int main()
{
    Factory factory;
    factory.Register("Concrete", [](){ return new Concrete;});

    auto instance = factory.Create("Concrete");

}
hansmaad
  • 18,417
  • 9
  • 53
  • 94