Reputation: 155
[A follow up to this question: Possible to instantiate object given its type in C++?
In Java, you can have a method parameter of type Class, and callers can pass in Foo.class. I don't consider this aspect reflection, though what you can do with the passed-in Class obviously is. Does C++ have any mechanism for passing in a "type"? Since I know there is little/nothing I could do with that passed-in type, I suspect the answer is "no".
Obviously, templates provide this facility, but they're not what I'm looking for.
Upvotes: 3
Views: 328
Reputation: 106539
No. This feature is part of "reflection" and is only possible in languages like Java which actually put information about classes in the compiled binary.
C++ (typically) does not actually store any information about classes at all in the resulting binary. (Excepting a few bits necessary for std::type_info
to work)
In reality, there's nothing like the "Type" provided by Java and friends available in C++, and therefore you cannot pass it to a method.
If you want to pass a type to a method for the purpose of instantiating it, you can actually do this in a better way (this works with Java and friends too)
#include <memory>
struct IMyType
{
virtual ~IMyType();
virtual MyMethod();
};
struct IElementFactory
{
virtual std::auto_ptr<IMyType> GetNewItem() const = 0;
virtual ~IElementFactory();
};
void MyMethodThatAcceptsAType(const IElementFactory& factory)
{
std::auto_ptr<IMyType> instance(factory.GetNewItem());
//Use your instance like normal.
}
This is better even in Java land because this code maintains type safety, while the reflection based code does not.
Upvotes: 0
Reputation: 143154
Sounds like RTTI (run-time type identification) is what you're looking for. From http://en.wikibooks.org/wiki/C++_Programming/RTTI :
The typeid operator, used to determine the class of an object at runtime. It returns a reference to a std::type_info object, which exists until the end of the program, that describes the "object".
Upvotes: 4