F
flopbucket
Hi,
I have a question about using a typeid comparison instead of
dynamic_cast in certain circumstances.
Assume I have the following:
class Base {};
class Foo : public Base {};
I can not change either Base or Foo. However, when a Foo object is
received, some special processing must occur. There is a method such
as:
void func(Base *b);
Calls to 'func' are always done with a Base * even if the real object
is a Foo (base class pointer).
Now, I know I could do:
void func(Base *b)
{
if(Foo *f=dynamic_cast<Foo*>(b))
{
// handle Foo
}
....
}
But I could also do (I believe)
void func(Base *b)
{
if(typeid(*b) == typeid(Foo))
{
/// handle Foo
}
}
My questions are:
1. Wouldn't the second version be quicker? My understand is that
dynamic_cast has to do more, since it allows you to cast throughout
the hierarchy.
2. Regardless of the two implementations above, can you think of a
better solution? I hate to do this typeid comparison or a
dynamic_cast in every call. Ideally:
void func(Base *b);
void func(Foo *f);
would be perfect, and the compiler would call the correct one
depending on the calling type. But in this application, objects of
type Foo are returned by a factory by the base class pointer, so the
compiler will always call func(Base *).
Any ideas greatly apprecaited.
Thanks
I have a question about using a typeid comparison instead of
dynamic_cast in certain circumstances.
Assume I have the following:
class Base {};
class Foo : public Base {};
I can not change either Base or Foo. However, when a Foo object is
received, some special processing must occur. There is a method such
as:
void func(Base *b);
Calls to 'func' are always done with a Base * even if the real object
is a Foo (base class pointer).
Now, I know I could do:
void func(Base *b)
{
if(Foo *f=dynamic_cast<Foo*>(b))
{
// handle Foo
}
....
}
But I could also do (I believe)
void func(Base *b)
{
if(typeid(*b) == typeid(Foo))
{
/// handle Foo
}
}
My questions are:
1. Wouldn't the second version be quicker? My understand is that
dynamic_cast has to do more, since it allows you to cast throughout
the hierarchy.
2. Regardless of the two implementations above, can you think of a
better solution? I hate to do this typeid comparison or a
dynamic_cast in every call. Ideally:
void func(Base *b);
void func(Foo *f);
would be perfect, and the compiler would call the correct one
depending on the calling type. But in this application, objects of
type Foo are returned by a factory by the base class pointer, so the
compiler will always call func(Base *).
Any ideas greatly apprecaited.
Thanks