Reputation: 579
How to define variable according to string. I had defined many classes.But I want to creat variable of this class according to some string.
The code looks like this.
class AA {};
class BB {};
class CC {
CC(void *pt);
virtual ~CC();
};
......
void test(char *ss,void *pt=NULL) {
//??????How to do?
}
int main() {
a1=test("AA"); //a1=new AA();
a2=test("AA"); //a2=new AA();
b1=test("BB"); //b1=new BB();
c1=test("CC",pt); //c1=new CC(pt);
}
Orther,you can consider this as URL and handle function.The std::map is common method to get instance of class according to string.But can't create a new instance to variable. I hope get a new instance according to string.
Upvotes: 0
Views: 245
Reputation: 24382
Maybe instead of using string names of types - use types as they are. To do this - use templates.
class AA {};
class BB {};
class CC {
public:
CC(void *pt) {}
virtual ~CC() {}
};
template <class T>
T* test() {
return new T();
}
template <class T>
T* test(void *pt) {
return new T(pt);
}
int main() {
void* pt;
AA* a1=test<AA>(); //a1=new AA();
AA* a2=test<AA>(); //a2=new AA();
BB* b1=test<BB>(); //b1=new BB();
CC* c1=test<CC>(pt); //c1=new CC(pt);
}
Upvotes: 0
Reputation: 153820
You probably want you function to return something, either void*
or, preferably, a [smart] pointer to a common base. The string should probably be passed as char const*
or as std::string const&
. Within the function you either directly compare the argument and you call the appropriate allocation or you create a std::map<std::string, FactoryFunction>
to look up a factory function based on the string.
Upvotes: 1
Reputation: 258568
C++ is a strongly typed language, so this isn't possible as you have it now.
Best case, you'd use a common base class for AA
, BB
, CC
and then use a factory. You can't just write:
a1=test("AA"); //a1=new AA();
a2=test("AA"); //a2=new AA();
b1=test("BB"); //b2=new BB();
c1=test("CC",pt); //b2=new CC(pt);
without defining a type for the variables.
For example:
class Base{};
class AA : public Base {};
class BB : public Base {};
Base* create(const std::string& what)
{
if (what == "AA")
return new AA;
if (what == "BB")
return new BB;
return NULL;
}
int main()
{
Base* a;
a = create("AA");
}
Alternitively, you should use smart pointers. If you don't you'll have to manage the memory yourself.
Upvotes: 5