?
=?ISO-8859-1?Q?Erik_Wikstr=F6m?=
Hi all,
I tried to store a std::type_info value in my code so I didn't have to
call typeid more than once when checking if a polymorphic object is of
one of certain types, like this:
#include <typeinfo>
class A
{
public:
virtual int foo() { return 42; }
};
class B : public A
{};
class C : public A
{};
void foo(A& obj)
{
std::type_info type(typeid(obj));
if(type==typeid(B)) { ... }
if(type==typeid(C)) { ... }
}
I found, however, that the copy-constructor of type_info was private; is
it save to store the value by reference:
const std::type_info& type(typeid(obj)); ?
This compiles fine, but I'm not sure whether this stores the reference
to a temporary object which is no longer valid when the comparison happens.
Is is ok to do this with references? Or is there any other way to store
the type_info or do I have to insert typeid(obj) everywhere in the ifs?
Yes, a const reference can be bound to a temporary.
Or you can use & to get the address of the type_info object (typeid
returns a reference) but in that case you should use type_info's ==
operator and not compare addresses of type_info objects, i.e.
void foo(A& obj)
{
const std::type_info* type = &typeid(obj);
if(*type==typeid(B)) { std::cout << "B\n"; }
if(*type==typeid(C)) { std::cout << "C\n"; }
}