Operator overloading through UFCS doesn't work

Tommi tommitissari at hotmail.com
Sat Oct 13 08:06:12 PDT 2012


On Saturday, 13 October 2012 at 11:50:40 UTC, Maxim Fomin wrote:
> I think implementing UFCS operator overloading is problematic. 
> Firstly, you want to put this language addition too far.

I don't see this as taking UFCS functionality "further". Rather, 
I think it's simply more logical that with UFCS you could provide 
extra operator methods just like you can provide extra "regular" 
methods. I assumed that UFCS operator overloading would work for 
sure, and it seems arbitrary to me that it doesn't.


> Secondly, compiler needs to know whether operator was 
> overloaded or not. If it knows, it generates code to call 
> "opSomething", if nor - it just doesn't generate anything. Now, 
> imagine what would happen if you write in some module "free" 
> function, supposed to hijack operator overloading method of 
> class or struct in another module. If you compile them 
> together, operator would be overloaded, if separately - nothing 
> would happen. This means that operator overloading would depend 
> on with what you compile your module - sometimes nothing would 
> be overloaded, sometimes it would be with one function, 
> sometimes with another.

You use the word "hijack", but free functions can't hijack 
anything. They can only provide new functionality. The situation 
you describe is exactly parallel to using UFCS (with regular 
functions) like this:

//File: mystruct.d
module mystruct;

struct MyStruct
{
     int _value;
}

//File: incr1.d
module incr1;

import mystruct;

void incr(ref MyStruct ms)
{
     ms._value += 1;
}

//File: incr2.d
module incr2;

import mystruct;

void incr(ref MyStruct ms)
{
     ms._value += 2;
}

//File: main.d
module main;

import std.stdio;
import mystruct;

static if (true) // change to false to print "2"
     import incr1;
else
     import incr2;

void main()
{
     MyStruct ms;
     ms.incr();
     writeln(ms._value); // prints "1"
}


> Thirdly, I see no reason in allowing it - for what purpose does 
> you proposal service for?

The main reason to me is that it would make more sense. It'd seem 
more logical that way. I can't think of any use cases.


More information about the Digitalmars-d-learn mailing list