Static operator overloads
Stuart Murray
stuart.w.murray at fakey.spambot.avoiding.gmail.com
Tue Jun 5 03:19:13 PDT 2007
torhu Wrote:
> Stuart Murray wrote:
> > Hi everyone
> > I'm a newbie to D and I've spent some time in the last few days messing around, seeing how things work.
> >
> > I noticed in a news posting that you can overload operators statically..
> > i.e.
> >
> > ///////////////
> >
> > class Test
> > {
> > private char[] memstring;
> >
> > this(char[] newstring)
> > {
> > memstring = newstring.dup;
> > }
> >
> > char[] toString()
> > {
> > return memstring;
> > }
> >
> > static Test opCat(char[] newstring)
> > {
> > return new Test(newstring);
> > }
> >
> > /+
> > Test opCat(char[] newstring)
> > {
> > return new Test(memstring ~ newstring);
> > }
> > +/
> > }
> >
> > int main(char[][] args)
> > {
> > Test bob = Test ~ "hello there";
> > writefln(bob);
> > return 0;
> > }
> >
> > ////////////////
> >
> > Browsing through the documentation I didn't come across any mention that static member operators were supported. I was just wondering if they are in fact intentional?
> >
> > Also:
> > I notice that having 2 member functions with the same signature, one static and one not, does not work (compiler claims it a conflicts). In particular, the above case, when the non-static opCmp is uncommented it will no longer compile.
> >
> > Is there any notes in the documentation to this effect? because I could not find any.
> >
> > Thanks for any reply.
> >
>
> I haven't seen this either. Are you sure that your static opCat
> actually works, and is in fact static? That compiler allows you to put
> 'static' in several places where it has no effect. I know that static
> opCall makes sense for structs, but that's about it when it comes to
> static operator overloads. Besides, your code won't even compile,
> because there's no default constructor.
The above compiled immediately before I pasted into my message. The only thing missing is import std.stdio.
I am fairly sure it is being used statically. Swapping the static form for the non-static form results in a compile error (because Test~"" would need to be replaced by new Test("")~""). In the section:
Test bob = Test ~ "hello";
No constructor is invoked directly, the constructor this(char[]) is used through the static opCat overload.
At least, thats how I read it.
More information about the Digitalmars-d-learn
mailing list