0

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?

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
spooja__
  • 133
  • 7
  • Templates have nothing to do with this, the same thing can be demonstrated without using any templates. In any case, if you really want to avoid casting `base*` to `derived*`, use `virtual` methods. For instance, `base` could have a `virtual` method that returns a `std::variant`, and then `derived` can override it to return the appropriate type, and then you can call `doSomething()` depending on what the `variant` is actually holding. Or, `base` could have a `virtual` method that `doSomething()` is passed to as a callback, and then `derived` can override it to call `doSomething()` as needed. – Remy Lebeau Aug 26 '21 at 19:43

0 Answers0