Skip to main content
gamedev.net
🔒 Locked

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

Started by thedustbustr Jul 3, 2008 at 11:38 AM 1 replies 1.4k views
Original Post
thedustbustr
thedustbustr
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;}
}
CmpDev
CmpDev
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.
thedustbustr
thedustbustr
Good info, I haven't thought it all the way through - I've never used typeid before. At this point I am most concerned with making it easy to expose in .NET...

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.