bhassink
bhassink

Reputation: 11

How to determine type compatibility for a mixin template of a non-polymorphic type

If I have a mix-in defined as...

template<class T> class Mixin : public T
{
    // mixin methods and members
};

...and declare it with T being a non-polymorphic class...

Mixin<NonPoly> mixin;

..and then have a base class pointer to it...

NonPoly* nonPolyPtr = &mixin;

...how can I later ensure nonPolyPtr is pointing to a Mixin type?

dynamic_cast<Mixin*>(nonPolyPtr)

The above does not compile because the base class is non-polymorphic.

I saw Boost has some trait classes that may help, but I'm hoping there's a simpler solution I'm overlooking.

Upvotes: 1

Views: 260

Answers (2)

ex0du5
ex0du5

Reputation: 2634

I think you are looking at the wrong requirements. You don't need to do any casting here, but you may need to do some restructuring of your code. If you have a relationship of classes A, which creates mixin and B which uses NonPoly, then just pass B the NonPoly pointer and use the mixin directly in A. There should be no reason to give up the type information in A just to try to get it back again. If there are more classes, separate them into those who know the mixin and those who know NonPoly, and it's the same relationship.

And it is very likely that if this is the case in the first place, a mixin design is not the proper approach. Very often, mixins are used when simple containment is needed. In my example with A and B above, you may have a Mixin class

template <typename T>
class Mixin
{
  T * GetObject()
  { return & t_; }

  // other methods that use t_
private:
  T t_;
};

and then just pass the object when it needs to be operated on. Or even more common, if you are just passing T to some 3rd party library, you need no mixin at all. Containment might not even be best. The best way to maintain encapsulation is always to write file-scope algorithms when you can manipulate the type T through it's public interface and public 3rd party routines.

If you can explain why you think you need to lose the type information and then later recover, we might be able to show more clearly how you can restructure ownership so that doesn't need to happen, but since this type information never leaves the runtime (since you are looking to cast - your question implies it's not getting serialised or anything), I can assure you that there is some design where that type information is not lost in the first place.

Upvotes: 2

JohnPS
JohnPS

Reputation: 2636

If you are certain of its type just use static_cast to downcast. You also need to specify the template parameter in the cast Mixin<NonPoly>*.

template<class T>
class Mixin : public T
{
    // mixin methods and members
};

class NonPoly {
};

int main() {
  Mixin<NonPoly> mixin;
  NonPoly* nonPolyPtr = &mixin;

  Mixin<NonPoly>* mixinPtr = static_cast<Mixin<NonPoly>*>(nonPolyPtr);
}

Upvotes: -1

Related Questions