How can we create an instance in C++ by a string type name?
Suppose we only have a string
string typename = "int"
How can we get 开发者_开发知识库an instance by this typename.
In C++ you cannot have a type just from a string
(or character array). Type must be declared at compile time.
[P.S. typename
is a keyword in C++, so it cannot be used as variable.]
This is not directly supported in C++. You could use the Abstract Factory Pattern
(see the Wikipedia article for it) and map the names of the class to the factory to create it.
You cannot do this directly in C++.
The usual way it's done is registering all possible types in some factory that will create the data on the heap.
精彩评论