开发者

Non-polymorphically Invoke Instance Method in D?

How do you statically invoke a particular definition of an instance method from outside the class of the o开发者_如何学JAVAbject, so as to inhibit polymorphism in that particular use? (In other words: I need the equivalent of Visual Basic.NET's MyClass, but from the outside.)


You can force the call by building a delegate and calling it. From memory:

void delegate(int, float) dg;

dg = &t.theFunction;  // gives the function for the dynamic type
// OR
dg.ptr = t;  // gives the object

dg.funcptr = &typeof(t).theFunction; // gives the function for the static type 

dg(1,3.1415);

OTOH this is a hack in my book and for some types will be sure to cause problems.


Is there a reason you are using polymorphic class methods when that isn't the behavior you desire? I'm also not sure what you mean by outside the class (is it that you want to call a member function without an instance of the object)?

I'll make some assumptions that what you probably should do is write normal functions which take objects as a first parameter.

binarySize(MyClass myObject) {  ... }

A feature that hasn't yet been added to any D compiler is the ability to call this like so:

myObject.binarySize();


you can use typeof(this).myfunc() inside class instance function to make non virtual call. If you need to call virtual method non-virtually from outside class, you can add new (final) method to class which will wrap the call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜