I tried to implement template polymorphism in order to conditionally initialize a template class object. Now I have to access a member variable of the template class, but I'm not sure how I can do that here.
class base
{
public:
base();
virtual ~base();
};
template <typename T>
class derived : public base
{
T derived_member;
}
...
void init(base*& base)
{
if (flow1)
base = new derived<int>();
else if (flow2)
base = new derived<string>();
else if (flow3)
base = new derived<float>();
else
base = new derived<userdefined_type>();
}
void func1()
{
base* b = NULL;
init(b);
// I want to access derived_mem of derived class .
// But I'm not understanding a better way to do something like this without typecasting base to
// derived , is there a better way to do this ? The below code defeats the whole point of template
// polymorphism I believe
if (flow1)
doSomething((derived_mem<int>*)(b));
else if (flow2)
doSomething((<derived_mem<string>*>)(b));
.....
}
I'm thinking if some way I can understand how to overload the access operator here, maybe I can do this, but I'm not too sure about it. I'm not exactly interested in writing a get() function to access derived_member, as I'm dealing with legacy code.
Is there a better way to do this?