Static operator overloads are possible why?
Bill Baxter
dnewsgroup at billbaxter.com
Fri Jun 29 16:07:47 PDT 2007
Just a couple of quick comments about your post:
1) It looks like you're reinventing std.signals.
2) The usual operator for adding another handler onto a list is ~=
(opCatAssign) not +=.
--bb
Giles Bathgate wrote:
> Dear Mr Bright;
>
> I have been playing with D and have come across what I believe to be a bug/feature idea.
>
> It all started when I tried to emulate C# Style events, (Dont worry this is not a request to add events to the language)
> I was really impressed by the power of the D language and found that I could make what microsoft call Multicast delegates
> So in my opinion there is no need to add them.
>
> However,
>
> the way I add handlers to the multicast delegate is using the following syntax:
>
> this.add_Paint = new PaintEventHandler(&Form1_Paint);
>
> as opposed to microsofts syntax of
>
> this.Paint += new PaintEventHandler(Form1_Paint);
>
> So I started investigating using opAddAssign overloads.
>
> Ok Introduction over Let me get to the point.
>
> Consider the following code:
>
>
> public class Test
> {
> public char[] Name;
>
> public Test opAddAssign(Test value)
> {
> writefln(value.Name);
> //TODO...
> }
> }
>
> int Main()
> {
> Test t;
> Test b = new Test();
>
> t += b; //Runtime exception because t is null
>
> }
>
> This code obviously has a runtime exception because t was not assigned and the translation of the code t += b; becomes
> t.opAddAssign(b); 'ok I thought', I shall make the operator overload static...'er no wait can I do that?'
>
> half expecting a compile error I tried anyway
>
>
> public class Test
> {
> public char[] Name;
>
> public static Test opAddAssign(Test value)
> {
> writefln(value.Name);
> //TODO...
> }
> }
>
> int Main()
> {
> Test t;
> Test b = new Test();
> b.Name = "foo"
>
> t += b; // Translates to: Test.opAddAssign(b);
>
> }
>
> output: foo
>
> The code compiles, and runs, and opAddAssign actually gets called,
>
> but wait surely t += b; translates to Test.opAddAssign(b);
>
> So how is that in anyway usefull? we have no reference to t, within our operator overload call.
> (In the first example the reference to t could have been referenced by this)
>
> So my question; 'should static operator overloads even be allowed?'
> and if they were to be allowed should they not have two arguments?
>
> thus:
>
> static Test opAddAssign(Test t, Test value){...}
>
>
> then
>
> t += b;
>
> becomes
>
> Test.opAddAssign(t,b);
>
> Static operator overloads would be useful to me for this one particular application.
> Whats you view?
>
> Regards
>
> Mr _Bathgate;
More information about the Digitalmars-d
mailing list