zl2k ha scritto:
This sounds a lot like Java-influenced thinking.
Perhaps, but the design would be just as bad in Java as in C++. In
\nearly\ all well designed programs, you should not explicitly query
an object for its type as part of normal operations. Dynamic dispatch
through virtual functions, aka Object Oriented programming, is there
specifically to avoid querying an object for its type then switching
on that type to do something different for each type. I have no simple
answer for the OP. We would need to know a lot about the problem
domain to offer a good design alternative.
Let me put this another way. To the OP: First, your question is
legitimate, and the literal answer is: "You are correct. C++ offers no
way to get the type of an arbitrary object at runtime. If you have a
Foo*, and it's a polymorphic class, then you can use dynamic_cast and/
or typeid to get the type."
However, asking the question suggests that you are pursuing a bad
design. In C++ and Java, the standard library containers are
homogeneous - they hold objects of the same type. In C++, you can have
a vector<Foo*>. It holds only pointers to Foo objects, which can point
to Foo objects, objects of derived type, and so on. In Java, the
situation is the same. You can have an ArrayList<Foo>, which holds
"references" to Foo objects, objects of derived type, and so on.
So, why do you want to put an object into a container, forget about
it, and have some unrelated code take one of the objects out of the
same container, and then try to do some derived-type specific logic to
it? This has alarm bells going off for bad design. For example, see
the C++ FAQ, specifically see the Circle And Ellipse problem, which
you may be doing.
http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.7