Cleanest way to handle this casting situation

21 views Asked by At

I have a base class and a derived class. The derived class is passed in as a templated parameter for another class, let's call it ObjectList. The templated parameter for this class is always expected to be of a type derived from BaseClass. The for in myFunc will not compile since GetAddrOfNext returns type BaseClass but the variable pp is defined of type T **.

I could downcast ((*pp)->GetAddrOfNext()) using a dynamic_cast but I was wondering if there is a cleaner way to handle this situation.

class BaseClass
{
public:
    BaseClass ** GetAddrOfNext() {return &mpNext;}
private:
    BaseClass * mpNext;
};

class DerivedClass : public BaseClass
{
...
};

template <class T>
class ObjectList
{
public:
...
     T * myFunc()
     {
     ...
         for (T ** pp = &(mpFirst); *pp != nullptr; pp = ((*pp)->GetAddrOfNext()))
         {
         ...
         }
     }

private:
    T* mpFirst;
0

There are 0 answers