Sign in to follow this  
thedustbustr

[.net] C++/CLI wrapper for polymorphic model

Recommended Posts

Use case:
ManagedSuper *s = GetSomething();
if (typeid(*s).name() == "Derived1") DoSomething(s->d1);
if (typeid(*s).name() == "Derived2") DoSomething(s->d2);
Is this a reasonable use case? Better way to do it? I want to have a unified list of Super*s which can be either Derived1 or Derived2, and I want to know which it is, because its not doing polymorphic things so much as it is storing data. perhaps boost::variant is a better idea? Anyway, is this the right idea to wrap my C++ model so I can use it in C#?
struct Super {};
struct Derived1 : public Super {int d1;};
struct Derived2 : public Super {int d2;};

//..........

public ref struct ManagedSuper {Super* super; ctor; dtor;};
public ref struct ManagedDerived1 : public ManagedSuper
{
ManagedDerived1(){Super* derived1 = new Derived1;}
~ManagedDerived1(){delete derived1;}
}
public ref struct ManagedDerived1 : public ManagedSuper
{
ManagedDerived2(){Super* derived2 = new Derived2;}
~ManagedDerived2(){delete derived2;}
}

Share this post


Link to post
Share on other sites
There are times when you may use such a feature, yet just not as you are showing as there is no guarantee the typeid will have the correct name (as it is implementation defined what name it will get and if it is unique) and Super does not have a data type d1 or d2


if (typeid(*s) == typeid(Derived1) ) DoSomething(static_cast<Derived1>(s)->d1);
...
edit actually this is nonsense as you can not use typeid like this,instead you would have to create a temporary object of the type.



Or use a dynamic cast

Derived d1(0);
if ( (d1= dynamic_cast<Derived1>(s) ) /*may need !=0 here or get an assignment warning*/ ) DoSomething(d1->d1);
...




As I said there are times when you may need to use these types of methods but "generally" it is a sign of poor design and there are methods of avoiding such code. Like moving some information up the tree depending on the situation you may move the do to the super class and have it supply the required type to the function (similar to a double dispatch pattern) or by using a design pattern.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this