dotNeter said:
Btw, the programming language I used is Objective C, not supports RTTI
built-in.
As I recall Objective-C has classes as objects, meaning you can
actually assign a class to a variable or return it from a function.
This allowed things such as [[var class] new]. You can't do this in
C++; it just isn't there (for more reasons than the one we are
concerned with here). What we have is what the last two parts of RTTI
stand for, "Type _Information_". There is just no way to store a type
in C++.
Now, to create the kind of behavior that [[var class] new] provides you
can use the Prototype pattern:
class X
{
public:
X* makeNew() { return new X(); }
};
X x;
X* px = x.makeNew();
You will never be able to create an equivelant to [var class] but you
can create equivelents for its common uses through Prototype.
You could create a template as a generic prototype:
template <typename T>
class Prototype
{
public:
T* makeNew() { return new T(); }
T make() { return T(); }
};
Then you could make a map and store these prototypes in it based on
information passed back from RTTI through the use of boost::any or an
abstract base for Prototype. However, better to just learn how your
general problem can be solved in C++ rather than trying to implement it
as you would in Objective-C.
In short, you cannot store a "type" anywhere. You can do certain
things at compile time that resolve types and this provides a
compile-time polymorphism...but that type must be available at time of
compile and not be ambiguous. RTTI will tell you what type you have
but this is not in a form that is useful for generating new objects of
that type...it can be passed to a system that is, but it itself won't.
As a "static language", C++ has rather limited type information at
runtime.