Consider the following:
struct B { };
template<typename T>
struct D : B
{
T t;
}
void g(int i) { ... }
void g(string s) { ... }
void g(char c) { ... }
void f(B* b)
{
if (dynamic_cast<D<int>*>(b))
{
g(dynamic_cast<D<int>*>(b)->t);
}
else if (dynamic_cast<D<string>*>(b))
{
g(dynamic_cast<D<string>*>(b)->t);
}
else if (dynamic_cast<D<char>*>(b))
{
g(dynamic_cast<D<char>*>(c)->t)
}
else
throw error;
};
Here there are only three possible types of T - int, string, char - but if the list of possible types were longer, say n, the if else chain would take O(n) to execute.
One way to deal with this would be to store an extra type code in D somehow and then switch
on the type code.
The RTTI system must already have such a code. Is there someway to get access to it and switch on it?
Or is there a better way to do what I'm trying to do?
f
withstruct D { virtual void f() { g(t) } }
, but this misses the larger problem. – Tieck