Static operator overloads

torhu fake at address.dude
Tue Jun 5 03:13:09 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.

Sorry, it compiles.  And prints "hello there".  But it doesn't do what 
opCat is supposed to do, since it doesn't concatenate anything.  So it's 
might just accidental that the compiler allows this code at all.  It 
doesn't make much sense.


More information about the Digitalmars-d-learn mailing list