Operator overhaul

Michel Fortin michel.fortin at michelf.com
Tue Oct 21 20:05:56 PDT 2008


On 2008-10-21 22:24:08 -0400, Andrei Alexandrescu 
<SeeWebsiteForEmail at erdani.org> said:

> I agree. Anyhow, the floor is open for suggestions on how to overhaul 
> the entire operator business. I'll tell you what is, to me, clearly 
> dead wrong: whenever one implements any class that wants to overload a 
> bunch of operators (number-like classes etc.) inevitably it boils down 
> to repetitive code like this:
> 
> struct Whatever
> {
>      Whatever opAdd(Whatever rhs) { return member + rhs.member; }
>      Whatever opSubtract(Whatever rhs) { return member - rhs.member; }
>      ...
> }
> 
> and lines and lines of brain damaged repetition, repetition, 
> repetition. If we add opWhateverAssign that will get even worse. The 
> challenge is, then, to define a way to overload operators that makes 
> the classic applications of the feature short and sweet.

Not terribly difficult. Add the op keyword, which could work both as a 
function name and an operator substitute inside the operator function:

struct Whatever
{
	Whatever op(+,-,/,*)(Whatever rhs) { member op rhs.member; return this; }
	auto op(=,+=,-=,/=,*=)(Whatever rhs) { member op rhs.member; return member; }
	auto op([])(int index, T value) { return member[index]; }
	// This one is a template:
	auto op([]=,[]+=,[]-=,[]/=,[]*=)(T)(int index, T value) { return 
member[index] op value; }
}

The sad thing is that then we lose the meaningful names, so perhaps 
this would be more in order:

struct Whatever
{
	Whatever opAdd,opSub,opDiv,opMul(Whatever rhs) { op(member, 
rhs.member); return this; }
	auto opAssign,opAddAssign,opSubAssign,opDivAssign,opMulAssign(Whatever 
rhs) { op(member, rhs.member); return member; }
	auto opIndex(int index, T value) { return member[index]; }
	// This one is a template:
	auto 
opIndexAssign,opIndexAddAssign,opIndexSubAssign,opIndexDivAssign,opIndexMulAssign(T)(int 
index, T value) { return op(member[index], value); }
}

Hum, no, sadly this one doesn't cut it. :-/

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list